题目链接:
力扣
题目详情:
37. 解数独t编写一个程序,通过填充空格来解决数独问题。
数独的解法需 遵循如下规则:
- 数字
1-9
在每一行只能出现一次。 - 数字
1-9
在每一列只能出现一次。 - 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 '.'
表示。
示例 1:
输入:board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]] 输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]] 解释:输入的数独如上图所示,唯一有效的解决方案如下所示:
提示:
board.length == 9
board[i].length == 9
board[i][j]
是一位数字或者'.'
- 题目数据 保证 输入数独仅有一个解
思路:
我们使用三个boolean数组,多开一个位置让下标与数字映射
rowCheck = new boolean[9][10];
colCheck = new boolean[9][10];
check = new boolean[3][3][10];
- boolean[][] rowCheck,用来表示某一行是否能填写某个数字:比如rowCheck[3][4]就表示下标为3这一行是否存在4这个数字,如果为false,就表示不存在
- boolean[][] colCheck;同上,表示某一列是否能填写某个数字
- boolean[][][] check;用来表示某一个小方块是否能填写某个数字,像下面这样把数度分为九个小方块,我们可以使用横坐标以及纵坐标/3的值来表示具体是哪个方块,比如下标为【3】【3】就可以使用check[3/1][3/1]来表示,那么check[3/1][3/1][4]就用来表示第一个小方块中是否存在4这个数字
确定好了Boolean数组的表示含义,我们就可以来写代码了,在写代码之前,我们需要先遍历数独中写好的数据,修改我们的Boolean数组,代码如下:
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '0';
rowCheck[i][num] = colCheck[j][num] = check[i/3][j/3][num] = true;
}
}
}
这样在调用我们写的dfs(char[][] board)方法,
完整代码(有详细注释):
class Solution {
boolean[][] rowCheck, colCheck;
boolean[][][] check;
public void solveSudoku(char[][] board) {
rowCheck = new boolean[9][10];
colCheck = new boolean[9][10];
check = new boolean[3][3][10];
// 遍历数独初始化Boolean数组
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '0';
rowCheck[i][num] = colCheck[j][num] = check[i/3][j/3][num] = true;
}
}
}
dfs(board);
}
public boolean dfs(char[][] board) {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
// 如果等于'.'说明需要填写数字
if (board[row][col] == '.') {
// 遍历数字1-9,选取合适的
for (int num = 1; num < 10; num++) {
// 如果行列以及所处小方块都不存在当前的数字,说明可以放
if (!rowCheck[row][num] && !colCheck[col][num] && !check[row/3][col/3][num]) {
// 修改当前的数字
board[row][col] = (char)(num+'0');
// 修改当前行列以及小方块的Boolean值
rowCheck[row][num] = colCheck[col][num] = check[row/3][col/3][num] = true;
// 如果接下来返回的为true,说明当前选择是正确的
if (dfs(board)) {
return true;
} else {
// 否则说明选择错误,就需要回溯到指定的位置,重新进行选择
board[row][col] = '.';
// 修改Boolean值回到初始状态
rowCheck[row][num] = colCheck[col][num] = check[row/3][col/3][num] = false;
}
}
}
// 走到这里说明数字1-9一个也不能填,直接返回false
return false;
}
}
}
//两层循环都走完说明数独全部填完,返回true
return true;
}
}