Skip to content

Commit 297c0b1

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 37_Sudoku_Solver.java
1 parent 637df66 commit 297c0b1

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Backtracking/37_Sudoku_Solver.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public void solveSudoku(char[][] board) {
3+
if (board == null || board.length == 0) {
4+
return;
5+
}
6+
7+
solve(board);
8+
}
9+
10+
private boolean isValid(char[][] board, int row, int col, char num) {
11+
int blockRow = (row / 3) * 3, blockCol = (col / 3) * 3;
12+
13+
for (int i = 0; i < 9; i++) {
14+
if (board[i][col] == num || board[row][i] == num || board[blockRow + i / 3][blockCol + i % 3] == num) {
15+
return false;
16+
}
17+
}
18+
19+
return true;
20+
}
21+
22+
private boolean solve(char[][] board) {
23+
for (int i = 0; i < board.length; i++) {
24+
for (int j = 0; j < board[i].length; j++) {
25+
if (board[i][j] == '.') {
26+
for (char c = '1'; c <= '9'; c++) {
27+
if (isValid(board, i, j, c)) {
28+
board[i][j] = c;
29+
30+
if (solve(board)) {
31+
return true;
32+
} else {
33+
board[i][j] = '.';
34+
}
35+
}
36+
}
37+
38+
return false;
39+
}
40+
}
41+
}
42+
43+
return true;
44+
}
45+
}

0 commit comments

Comments
 (0)