sudoku solver


Problem Description
这种回朔的题目都不怎么难,感觉关键点在于短时间内能不能写出bug-free来。

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
public void (char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9)
return;
dfs(board);
}

public boolean dfs(char[][]board) {
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[0].length; ++j) {
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; ++c) {
if (valid(board, i, j, c)) {
board[i][j] = c;
if (dfs(board)) {
return true;
} else {

// the previous level
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}

public boolean valid(char[][]board, int i, int j, char target) {
// check row and column
for (int index = 0; index < 9; ++index) {
char c = board[i][index];
if (c == target)
return false;
c = board[index][j];
if (c == target)
return false;
}
int row = (i / 3) * 3, column = (j / 3) * 3;
for (i = row; i < row + 3; ++i) {
for (j = column; j < column + 3; ++j) {
if (board[i][j] == target) {
return false;
}
}
}
return true;
}