数独求解 回溯算法
class Solution {
boolean[][] line = new boolean[9][9];
boolean[][] column = new boolean[9][9];
boolean[][][] block = new boolean[3][3][9];
boolean valid = false;
List<int[]> spaces = new ArrayList<>();
public void solveSudoku(char[][] board) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
spaces.add(new int[]{i, j});
} else {
int digit = board[i][j] - '1';
line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
}
}
}
dfs(board, 0);
}
public void dfs(char[][] board, int pos) {
//能到这一步,直接return,说明求解成功,每一次回溯都不会执行退回false的步骤
if (pos == spaces.size()) {
valid = true;
return;
}
int[] space = spaces.get(pos);
int i = space[0], j = space[1];
for (int digit = 0; digit < 9 && !valid; ++digit) {
/*只有满足数独要求的digit才能填入,line[i][digit]和column[j][digit]和block[i / 3][j / 3][digit]
都是false表示这个数还没有填过,取反才能运行下列代码*/
if (!line[i][digit] && !column[j][digit] && !block[i / 3][j / 3][digit]) {
//填过digit就把这个位置全都换为true,这样下次判断这个位置进入if语句再取反就是false了
line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = true;
board[i][j] = (char) (digit + '0' + 1);
dfs(board, pos + 1);
//能到这一步说明行不通,digit填入的位置全部改回false,并且随着回溯,每一个位置都退回false
line[i][digit] = column[j][digit] = block[i / 3][j / 3][digit] = false;
}
}
}
}
来源:LeetCode官方