-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSolveSudoku.java
59 lines (54 loc) · 1.58 KB
/
SolveSudoku.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package ds.backtrack;
/**
* 解数独
* LeetCode 37 https://leetcode-cn.com/problems/sudoku-solver/
*
* @author yangyi 2021年01月06日00:14:33
*/
public class SolveSudoku {
public void solveSudoku(char[][] board) {
backtrack(board);
}
private boolean backtrack(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != '.') {
continue;
}
for (char k = '1'; k <= '9'; k++) {
if (isValid(i, j, k, board)) {
board[i][j] = k;
if (backtrack(board)) {
return true;
}
board[i][j] = '.';
}
}
return false;
}
}
return true;
}
private boolean isValid(int row, int col, char value, char[][] board) {
for (int i = 0; i < 9; i++) {
if (board[row][i] == value) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if (board[i][col] == value) {
return false;
}
}
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == value) {
return false;
}
}
}
return true;
}
}