题目描述
Write a program to solve a Sudoku puzzle by filling the empty cells.
写代码解决数独问题。
A sudoku solution must satisfy all of the following rules:
数独规则如下:
- Each of the digits
1-9
must occur exactly once in each row.
1-9每行必须出现且只能出现一次 - Each of the digits
1-9
must occur exactly once in each column.
1-9每列必须出现且只能出现一次 - Each of the the digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid.
每个3*3的子格子内(粗框标记的),1-9必须出现且只能出现一次
Empty cells are indicated by the character'.'
.
Note:
- The given board contain only digits
1-9
and the character'.'
.
给出的数组中只有1-9
和'.'
- You may assume that the given Sudoku puzzle will have a single unique solution.
给出的数独只有一个唯一解 - The given board size is always
9x9
.
给的数组永远是9*9,不用多余的判断
思路分析
其实没啥更好的解法,就是DFS深度优先搜索找结果,
- 遍历格子,如果发现'.',就开始执行下面的操作:
- 从1到9依次填数,从填1开始,
- 然后看下行有没有问题,
- 看下列有没有问题,
- 看下3*3的子格子有没有问题,
- 都没问题就递归的往下找。
- 有问题(1,2,3当前格子填的数字冲突了,或者4当前格子的填数导致后面递归的填数失败了)就把这个位置换回'.'(这就是一个回溯的过程,因为这样一来之前递归的失败路径就全都回退了),然后改成填2,再继续遍历
- 如果1-9都遍历完,还是没有合适的,就返回false给上层。
代码实现
总之就是一个DFS搜索,注意下1,2,3条件的判断,然后想清楚什么时候递归(当前填数没问题,要确认下面层次的问题)以及递归的出口(当前位置1-9都遍历完还是没有合适的就返回false,如果9*9的格子全遍历完了中间没有返回false就说明数组中没有'.'了,填满了)就行了。
public class Solution {
/**
* 6 / 6 test cases passed.
* Status: Accepted
* Runtime: 17 ms
*
* @param board
*/
public void solveSudoku(char[][] board) {
solve(board);
}
private boolean solve(char[][] board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
for (int k = 0; k < 9; k++) {
board[i][j] = (char) ('1' + k);
if (isValid(board, i, j) && solve(board)) {
return true;
} else {
// backtracking to '.'
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board, int x, int y) {
for (int i = 0; i < board.length; i++) {
if (board[i][y] == board[x][y] || board[x][i] == board[x][y]) {
return false;
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int pos_x = x - x % 3 + i;
int pos_y = y - y % 3 + j;
if (x != pos_x && y != pos_y && board[x][y] == board[pos_x][pos_y]) {
return false;
}
}
}
return true;
}
}