Skip to content

Commit 906e1ab

Browse files
authored
Update SudokuSolver.java
Adds a solution for **LeetCode 37: Sudoku Solver** in Java. Solves a 9x9 Sudoku puzzle by filling empty cells using **backtracking**, ensuring all rows, columns, and 3x3 sub-boxes satisfy Sudoku rules.
1 parent 3322727 commit 906e1ab

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

Java/SudokuSolver.java

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,54 @@
11
class Solution {
22
public void solveSudoku(char[][] board) {
3-
backtrack(board);
3+
backtrack(board); // Start backtracking from the first cell
44
}
55

6+
// Backtracking function to fill empty cells
67
private boolean backtrack(char[][] board) {
78
for (int row = 0; row < 9; row++) {
89
for (int col = 0; col < 9; col++) {
9-
if (board[row][col] == '.') { // empty cell
10+
if (board[row][col] == '.') { // Found an empty cell
1011
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
1314

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
1617
}
1718
}
18-
return false; // no valid number
19+
return false; // No valid number, trigger backtracking
1920
}
2021
}
2122
}
22-
return true; // all cells filled
23+
return true; // All cells filled, Sudoku solved
2324
}
2425

26+
// Check if placing 'c' at board[row][col] is valid
2527
private boolean isValid(char[][] board, int row, int col, char c) {
2628
for (int i = 0; i < 9; i++) {
27-
// check row
29+
// Check row
2830
if (board[row][i] == c) return false;
29-
// check column
31+
// Check column
3032
if (board[i][col] == c) return false;
31-
// check 3x3 sub-box
33+
// Check 3x3 sub-box
3234
int subRow = 3 * (row / 3) + i / 3;
3335
int subCol = 3 * (col / 3) + i % 3;
3436
if (board[subRow][subCol] == c) return false;
3537
}
3638
return true;
3739
}
3840
}
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

Comments
 (0)