-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku solver.txt
62 lines (57 loc) · 1.96 KB
/
sudoku solver.txt
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
class Solution {
int n = 3, N = n * n;
int[] status;
char[][] board;
boolean solved = false;
public void solveSudoku(char[][] board) {
// status: [rows : cols : boxes]
status = new int[N * n];
this.board = board;
// fill the numbers
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] != '.')
placeNumber(board[i][j] - '0', i, j);
}
}
backtrack(0, 0);
}
public void backtrack(int i, int j) {
if (board[i][j] == '.') {
for (int d = 1; d < 10; d++) {
if (canPlace(d, i, j)) {
placeNumber(d, i, j);
afterPlace(i, j);
if (!solved) removeNumber(d, i, j);
}
}
} else
afterPlace(i, j);
}
public void placeNumber(int num, int i, int j) {
status[i] |= (1 << num);
status[N + j] |= (1 << num);
int box = 3 * (i / 3) + (j / 3) + 2 * N;
status[box] |= (1 << num);
board[i][j] = (char) (num + '0');
}
public void removeNumber(int num, int i, int j) {
status[i] ^= (1 << num);
status[N + j] ^= (1 << num);
int box = 3 * (i / 3) + (j / 3) + 2 * N;
status[box] ^= (1 << num);
board[i][j] = '.';
}
public void afterPlace(int i, int j) {
if (i == N - 1 && j == N - 1) solved = true;
else if (j == N - 1) backtrack(i + 1, 0); // move forward
else backtrack(i, j + 1);
}
public boolean canPlace(int num, int i, int j) {
if ((status[i] & (1 << num)) != 0) return false;
if ((status[N + j] & (1 << num)) != 0) return false;
int box = 3 * (i / 3) + (j / 3) + 2 * N;
if ((status[box] & (1 << num)) != 0) return false;
return true;
}
}