|
1 | 1 | class Solution { |
2 | 2 | public void solveSudoku(char[][] board) { |
3 | | - backtrack(board); |
| 3 | + backtrack(board); // Start backtracking from the first cell |
4 | 4 | } |
5 | 5 |
|
| 6 | + // Backtracking function to fill empty cells |
6 | 7 | private boolean backtrack(char[][] board) { |
7 | 8 | for (int row = 0; row < 9; row++) { |
8 | 9 | for (int col = 0; col < 9; col++) { |
9 | | - if (board[row][col] == '.') { // empty cell |
| 10 | + if (board[row][col] == '.') { // Found an empty cell |
10 | 11 | for (char num = '1'; num <= '9'; num++) { |
11 | | - if (isValid(board, row, col, num)) { |
12 | | - board[row][col] = num; // place number |
| 12 | + if (isValid(board, row, col, num)) { // Check if number is valid |
| 13 | + board[row][col] = num; // Place number |
13 | 14 |
|
14 | | - if (backtrack(board)) return true; // solved |
15 | | - board[row][col] = '.'; // backtrack |
| 15 | + if (backtrack(board)) return true; // Continue solving recursively |
| 16 | + board[row][col] = '.'; // Backtrack if dead-end |
16 | 17 | } |
17 | 18 | } |
18 | | - return false; // no valid number |
| 19 | + return false; // No valid number, trigger backtracking |
19 | 20 | } |
20 | 21 | } |
21 | 22 | } |
22 | | - return true; // all cells filled |
| 23 | + return true; // All cells filled, Sudoku solved |
23 | 24 | } |
24 | 25 |
|
| 26 | + // Check if placing 'c' at board[row][col] is valid |
25 | 27 | private boolean isValid(char[][] board, int row, int col, char c) { |
26 | 28 | for (int i = 0; i < 9; i++) { |
27 | | - // check row |
| 29 | + // Check row |
28 | 30 | if (board[row][i] == c) return false; |
29 | | - // check column |
| 31 | + // Check column |
30 | 32 | if (board[i][col] == c) return false; |
31 | | - // check 3x3 sub-box |
| 33 | + // Check 3x3 sub-box |
32 | 34 | int subRow = 3 * (row / 3) + i / 3; |
33 | 35 | int subCol = 3 * (col / 3) + i % 3; |
34 | 36 | if (board[subRow][subCol] == c) return false; |
35 | 37 | } |
36 | 38 | return true; |
37 | 39 | } |
38 | 40 | } |
| 41 | + |
| 42 | +/* |
| 43 | +Algorithm Description: |
| 44 | +1. Traverse the board to find an empty cell (denoted by '.'). |
| 45 | +2. Try placing digits '1' to '9' in the empty cell. |
| 46 | +3. For each number, check if it is valid in current row, column, and 3x3 sub-box. |
| 47 | +4. If valid, place the number and recursively attempt to solve the rest of the board. |
| 48 | +5. If a dead-end is reached, backtrack by resetting the cell to '.'. |
| 49 | +6. Repeat until all cells are filled correctly, yielding the solved Sudoku. |
| 50 | + |
| 51 | +Complexity Analysis: |
| 52 | +- Time Complexity: O(9^m), where m = number of empty cells (each empty cell can have up to 9 options). |
| 53 | +- Space Complexity: O(1) extra space (board modified in-place). Recursion stack can go up to O(m). |
| 54 | +*/ |
0 commit comments