Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

import javax.swing.

*;

import java.awt.*;

import java.awt.event.*;

public class SudokuGame extends JFrame {

private JTextField[][] cells;

private JButton solveButton;

private JButton clearButton;

public SudokuGame() {

setTitle("Sudoku Game");

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

JPanel sudokuPanel = new JPanel();

sudokuPanel.setLayout(new GridLayout(9, 9));

cells = new JTextField[9][9];

for (int i = 0; i < 9; i++) {

for (int j = 0; j < 9; j++) {

cells[i][j] = new JTextField();


sudokuPanel.add(cells[i][j]);

add(sudokuPanel, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel();

solveButton = new JButton("Solve");

clearButton = new JButton("Clear");

solveButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

solveSudoku();

});

clearButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

clearSudoku();

});

buttonPanel.add(solveButton);

buttonPanel.add(clearButton);
add(buttonPanel, BorderLayout.SOUTH);

setVisible(true);

private void solveSudoku() {

int[][] board = new int[9][9];

// Read the values from the text fields and populate the board array

for (int i = 0; i < 9; i++) {

for (int j = 0; j < 9; j++) {

String value = cells[i][j].getText();

if (!value.isEmpty()) {

board[i][j] = Integer.parseInt(value);

if (solve(board)) {

// If a solution is found, update the text fields with the solved values

for (int i = 0; i < 9; i++) {

for (int j = 0; j < 9; j++) {

cells[i][j].setText(String.valueOf(board[i][j]));

}
} else {

JOptionPane.showMessageDialog(this, "No solution found!");

private boolean solve(int[][] board) {

for (int row = 0; row < 9; row++) {

for (int col = 0; col < 9; col++) {

if (board[row][col] == 0) {

for (int num = 1; num <= 9; num++) {

if (isValid(board, row, col, num)) {

board[row][col] = num;

if (solve(board)) {

return true;

} else {

board[row][col] = 0;

return false;

return true;

}
private boolean isValid(int[][] board, int row, int col, int num) {

// Check if the number already exists in the same row or column

for (int i = 0; i < 9; i++) {

if (board[row][i] == num || board[i][col] == num) {

return false;

// Check if the number already exists in the same 3x3 subgrid

int startRow = row - row % 3;

int startCol = col - col % 3;

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

if (board[startRow + i][startCol + j] == num) {

return false;

return true;

private void clearSudoku() {

for (int i = 0; i < 9; i++) {


for (int j = 0; j < 9; j++) {

cells[i][j].setText("");

public static void main(String[] args) {

new SudokuGame();

You might also like