Sudoku Solver
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.
- Each of the digits 1-9 must occur exactly once in each column.
- Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
- Empty cells are indicated by the character ‘.’.
解析
给定一个9*9的表格,求解数独。用回溯的深度优先搜索算法,重点在于从左往右搜索,遇到行末就跳到下一行。先给出DFS的模板伪代码
/**
* DFS核心伪代码
* 前置条件是visit数组全部设置成false
* @param n 当前开始搜索的节点
* @param d 当前到达的深度
* @return 是否有解
*/
bool DFS(Node n, int d){
if (isEnd(n, d)){//一旦搜索深度到达一个结束状态,就返回true
return true;
}
for (Node nextNode in n){//遍历n相邻的节点nextNode
if (!visit[nextNode]){//
visit[nextNode] = true;//在下一步搜索中,nextNode不能再次出现
if (DFS(nextNode, d+1)){//如果搜索出有解
//做些其他事情,例如记录结果深度等
return true;
}
//重新设置成false,因为它有可能出现在下一次搜索的别的路径中
visit[nextNode] = false;
}
}
return false;//本次搜索无解
}
本题代码
class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
Sudoku(board, 0, 0);
}
bool Sudoku(vector<vector<char>>& board, int i, int j){
if(i==9) return true;
if(j==9) return Sudoku(board, i+1, 0);
if(board[i][j] == '.'){
for(int k=0; k<9; k++){
if(check(board, i, j, k+'1')){
board[i][j] = k+'1';
if(Sudoku(board, i,j+1))
return true;
board[i][j] = '.';
}
}
}
else
return Sudoku(board,i,j+1);
return false;
}
bool check(vector<vector<char>>& board, int i, int j, char ch){
for(int row=0;row<9;row++)
if(board[row][j] == ch)
return false;
for(int col=0;col<9;col++)
if(board[i][col] == ch)
return false;
for(int row=(i/3)*3; row<(i/3)*3+3; row++)
for(int col = (j/3)*3; col < (j/3)*3+3; col++)
if(board[row][col] == ch)
return false;
return true;
}
};
参考
https://leetcode.com/problems/sudoku-solver/discuss/15853/Simple-and-Clean-Solution-C%2B%2B