From 0cfd960edb3bdde2ab117166029ac4e03e32144e Mon Sep 17 00:00:00 2001 From: Prerna Jha <114309444+Jprerna04@users.noreply.github.com> Date: Tue, 29 Oct 2024 00:39:59 +0530 Subject: [PATCH] Create SudokuGame.java This Java program solves a 9x9 Sudoku puzzle using the backtracking algorithm. The solveBoard() method recursively tries numbers in empty cells, backtracking if a number placement violates Sudoku rules, as checked by isValidPlacement(). Once solved, printBoard() displays the completed puzzle in an organized format. --- JavaProjects/SudokuGame.java | 78 ++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 JavaProjects/SudokuGame.java diff --git a/JavaProjects/SudokuGame.java b/JavaProjects/SudokuGame.java new file mode 100644 index 0000000..d01aefb --- /dev/null +++ b/JavaProjects/SudokuGame.java @@ -0,0 +1,78 @@ +public class SudokuSolver { + private static final int GRID_SIZE = 9; + + public static void main(String[] args) { + int[][] board = { + {7, 0, 2, 0, 5, 0, 6, 0, 0}, + {0, 0, 0, 0, 0, 3, 0, 0, 0}, + {1, 0, 0, 0, 0, 9, 5, 0, 0}, + {8, 0, 0, 0, 0, 0, 0, 9, 0}, + {0, 4, 3, 0, 0, 0, 7, 5, 0}, + {0, 9, 0, 0, 0, 0, 0, 0, 8}, + {0, 0, 9, 7, 0, 0, 0, 0, 5}, + {0, 0, 0, 2, 0, 0, 0, 0, 0}, + {0, 0, 7, 0, 4, 0, 2, 0, 3} + }; + + if (solveBoard(board)) { + System.out.println("Sudoku solved successfully:"); + printBoard(board); + } else { + System.out.println("Unable to solve Sudoku."); + } + } + + private static boolean solveBoard(int[][] board) { + for (int row = 0; row < GRID_SIZE; row++) { + for (int col = 0; col < GRID_SIZE; col++) { + if (board[row][col] == 0) { + for (int num = 1; num <= GRID_SIZE; num++) { + if (isValidPlacement(board, num, row, col)) { + board[row][col] = num; + + if (solveBoard(board)) { + return true; + } else { + board[row][col] = 0; + } + } + } + return false; + } + } + } + return true; + } + + private static boolean isValidPlacement(int[][] board, int number, int row, int col) { + for (int i = 0; i < GRID_SIZE; i++) { + if (board[row][i] == number || board[i][col] == number) { + return false; + } + } + + int subgridRowStart = (row / 3) * 3; + int subgridColStart = (col / 3) * 3; + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + if (board[subgridRowStart + i][subgridColStart + j] == number) { + return false; + } + } + } + return true; + } + + private static void printBoard(int[][] board) { + for (int row = 0; row < GRID_SIZE; row++) { + if (row % 3 == 0 && row != 0) { + System.out.println("-----------"); + } + for (int col = 0; col < GRID_SIZE; col++) { + if (col % 3 == 0 && col != 0) System.out.print("|"); + System.out.print(board[row][col] == 0 ? "." : board[row][col]); + } + System.out.println(); + } + } +}