-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0037-sudoku-solver.java
More file actions
40 lines (33 loc) · 1.12 KB
/
0037-sudoku-solver.java
File metadata and controls
40 lines (33 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
private char [][] board;
public void solveSudoku(char[][] board) {
this.board = board;
helper(0, 0);
}
public boolean helper(int row, int col) {
if (col == 9) {
row += 1;
col = 0;
}
if (row == 9) return true;
if (board[row][col] != '.')
return helper(row, col + 1);
for (char i = '1'; i <= '9'; i++) {
if (!isValid(board, row, col, i))
continue;
board[row][col] = i;
if (helper(row, col + 1) == true)
return true;
board[row][col] = '.';
}
return false;
}
public boolean isValid(char[][] board, int row, int col, char c) {
for (int i=0; i<9; i++) {
if (board[i][col] != '.' && board[i][col] == c) return false;
if (board[row][i] != '.' && board[row][i] == c) return false;
if (board[3*(row/3)+i/3][3*(col/3)+i%3] != '.' && board[3*(row/3)+i/3][3*(col/3)+i%3] == c) return false;
}
return true;
}
}