|
| 1 | +package Java.algorithms.arrays; |
| 2 | + |
| 3 | +public class SudokuSolver { |
| 4 | + |
| 5 | + private static final int SIZE = 9; |
| 6 | + |
| 7 | + public void solveSudoku(char[][] board) { |
| 8 | + solve(board); |
| 9 | + } |
| 10 | + |
| 11 | + private boolean solve(char[][] board) { |
| 12 | + for (int row = 0; row < SIZE; row++) { |
| 13 | + for (int col = 0; col < SIZE; col++) { |
| 14 | + if (board[row][col] == '.') { |
| 15 | + for (char num = '1'; num <= '9'; num++) { |
| 16 | + if (isValid(board, row, col, num)) { |
| 17 | + board[row][col] = num; |
| 18 | + if (solve(board)) return true; |
| 19 | + board[row][col] = '.'; |
| 20 | + } |
| 21 | + } |
| 22 | + return false; |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + return true; |
| 27 | + } |
| 28 | + |
| 29 | + private boolean isValid(char[][] board, int row, int col, char num) { |
| 30 | + for (int i = 0; i < SIZE; i++) { |
| 31 | + if (board[row][i] == num || board[i][col] == num) return false; |
| 32 | + } |
| 33 | + int startRow = (row / 3) * 3; |
| 34 | + int startCol = (col / 3) * 3; |
| 35 | + for (int i = startRow; i < startRow + 3; i++) { |
| 36 | + for (int j = startCol; j < startCol + 3; j++) { |
| 37 | + if (board[i][j] == num) return false; |
| 38 | + } |
| 39 | + } |
| 40 | + return true; |
| 41 | + } |
| 42 | + |
| 43 | + private void printBoard(char[][] board) { |
| 44 | + for (int i = 0; i < SIZE; i++) { |
| 45 | + for (int j = 0; j < SIZE; j++) { |
| 46 | + System.out.print(board[i][j] + " "); |
| 47 | + } |
| 48 | + System.out.println(); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Simulates a C/C++ style int main() function |
| 54 | + */ |
| 55 | + public static int run() { |
| 56 | + char[][] board = { |
| 57 | + {'5','3','.','.','7','.','.','.','.'}, |
| 58 | + {'6','.','.','1','9','5','.','.','.'}, |
| 59 | + {'.','9','8','.','.','.','.','6','.'}, |
| 60 | + {'8','.','.','.','6','.','.','.','3'}, |
| 61 | + {'4','.','.','8','.','3','.','.','1'}, |
| 62 | + {'7','.','.','.','2','.','.','.','6'}, |
| 63 | + {'.','6','.','.','.','.','2','8','.'}, |
| 64 | + {'.','.','.','4','1','9','.','.','5'}, |
| 65 | + {'.','.','.','.','8','.','.','7','9'} |
| 66 | + }; |
| 67 | + |
| 68 | + SudokuSolver solver = new SudokuSolver(); |
| 69 | + solver.solveSudoku(board); |
| 70 | + solver.printBoard(board); |
| 71 | + |
| 72 | + return 0; // success |
| 73 | + } |
| 74 | + |
| 75 | + public static void main(String[] args) { |
| 76 | + int status = run(); |
| 77 | + System.exit(status); |
| 78 | + } |
| 79 | +} |
0 commit comments