Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'
.
You may assume that there will be only one unique solution.
A sudoku puzzle, and its solution numbers marked in red.
解题思路
采用回溯法(Backtracking)求解,代码如下:
class Solution {
private:
// 检测第 x 行,第 y 列是否有效
bool isValidSudoku(vector<vector<char>>& board, int row, int col) {
// 行
for(int j = 0; j < 9; j++)
if(j != col && board[row][j] == board[row][col])
return false;
// 列
for(int i = 0; i < 9; i++)
if(i != row && board[i][col] == board[row][col])
return false;
// 九宫格
int gridRow = row/3*3, gridCol = col/3*3;
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
if(gridRow + i != row && gridCol + j != col &&
board[gridRow + i][gridCol + j] == board[row][col])
return false;
return true;
}
bool internalSolver(vector<vector<char>>& board) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
// 若board[i][j] == '.',则尝试填入数字1-9
for (int k = 0; k < 9; ++k) {
board[i][j] = '1' + k;
// 当前填入的数字有效,递归解决余下部分
if (isValidSudoku(board, i, j)) {
if (internalSolver(board)) {
// 余下部分成功解决,则board已填充完全
return true;
}
}
}
//该空格无论设置什么数字都无法达到合法状态,回溯
board[i][j] = '.';
return false;
}
}
}
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
internalSolver(board);
}
};
这里提供了一个JavaScript实现的 Sudoku puzzle solver 和一些相关链接。