Poison

37. Sudoku Solver

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
66
67
68
69
70
class Solution {
public void solveSudoku(char[][] board) {
solveSudoku(board, 0);
}

private boolean solveSudoku(char[][] board, int index) {
int m = board.length, n = board[0].length;
if (index == m * n) {
return true;
}

int i = index / n, j = index % m;
if (board[i][j] == '.') {
for (char k = '1'; k <= '9'; k++) {
if (canFill(board, i, j, k)) {
board[i][j] = k;
if (solveSudoku(board, index + 1)) {
return true;
}
board[i][j] = '.';
}
}
} else {
return solveSudoku(board, index + 1);
}

return false;
}

private boolean canFill(char[][] board, int i, int j, char c) {
int m = board.length, n = board[0].length;

for (int rowIndex = 0; rowIndex < i; rowIndex++) {
if (board[rowIndex][j] == c) {
return false;
}
}
for (int rowIndex = i + 1; rowIndex < m; rowIndex++) {
if (board[rowIndex][j] == c) {
return false;
}
}

for (int colIndex = 0; colIndex < j; colIndex++) {
if (board[i][colIndex] == c) {
return false;
}
}
for (int colIndex = j; colIndex < n; colIndex++) {
if (board[i][colIndex] == c) {
return false;
}
}

int rowIndex = i / 3 * 3, colIndex = j / 3 * 3;
for (int k = rowIndex; k < rowIndex + 3; k++) {
for (int l = colIndex; l < colIndex + 3; l++) {
if (k == i && l == j) {
continue;
} else {
if (board[k][l] == c) {
return false;
}
}
}
}

return true;
}
}
Reference

37. Sudoku Solver