-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
65 lines (58 loc) · 1.83 KB
/
Solution.java
File metadata and controls
65 lines (58 loc) · 1.83 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package leetCode_37;
import java.util.Arrays;
/**
* @author dimdark
*/
public class Solution {
private boolean[][] columns = new boolean[9][9];
private boolean[][] rows = new boolean[9][9];
private boolean[][] boxes = new boolean[9][9];
public Solution() {
for (int i = 0; i < 9; ++i) {
Arrays.fill(columns[i], false);
Arrays.fill(rows[i], false);
Arrays.fill(boxes[i], false);
}
}
public void solveSudoku(char[][] board) {
int num;
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
if (board[i][j] != '.') {
num = board[i][j] - '0' - 1;
columns[j][num] = true;
rows[i][num] = true;
boxes[j / 3 + i / 3 * 3][num] = true;
}
}
}
backtrack(board, 0, 0);
}
private boolean backtrack(char[][] board, int x, int y) {
if (x == 9) {
return true;
}
int ny = (y + 1) % 9;
int nx = ny == 0 ? x + 1 : x;
int boxIdx = x / 3 * 3 + y / 3;
if (board[x][y] != '.') {
return backtrack(board, nx, ny);
}
for (int i = 1; i <= 9; ++i) {
if (!columns[y][i - 1] && !rows[x][i - 1] && !boxes[boxIdx][i - 1]) {
board[x][y] = (char)(i + '0');
columns[y][i - 1] = true;
rows[x][i - 1] = true;
boxes[boxIdx][i - 1] = true;
if (backtrack(board, nx, ny)) {
return true;
}
board[x][y] = '.';
columns[y][i - 1] = false;
rows[x][i - 1] = false;
boxes[boxIdx][i - 1] = false;
}
}
return false;
}
}