题目:
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.
分析与解答:
利用回溯法进行递归的DFS。判断每个位置是不是为'.'。不是就跳过,是就循环遍历1-9填在该位置的合理性。如果合理就继续下一个位置,如果尝试了所有9个数都不合理就回溯。我自己的代码AC了,虽然比较短但是逻辑不是很清晰,贴出一份别人的代码。
class Solution {
public:
void solveSudoku(vector<vector<char> > &board) {
solve(board, 0);
}
bool solve(vector<vector<char> > &board , int count) {//递归求解
if(count >= 81)
return true;
int row = count / 9, col = count % 9; //计算坐标
if(board[row][col] != '.')
return solve(board, count + 1);
else {
for(char c = '1'; c <= '9'; c++) {
if(isValidRow(board, row, c) && isValidCol(board, col, c) && isValidBox(board, row, col, c)) {
board[row][col] = c;
if(solve(board, count + 1))
return true;
else
board[row][col] = '.';
}
}
}
return false;
}
bool isValidRow(vector<vector<char> > &board, int row , char c) {
for(int i = 0; i < 9; i++) {
if(board[row][i] == c)
return false;
}
return true;
}
bool isValidCol(vector<vector<char> > &board, int col , char c) {
for(int i = 0; i < 9; i++) {
if(board[i][col] == c)
return false;
}
return true;
}
bool isValidBox(vector<vector<char> > &board, int row , int col, char c) {
int boxR = (row / 3) * 3 , boxC = (col / 3) * 3; //计算九宫格的第一个坐标
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(board[boxR + i][boxC + j] == c)
return false;
}
}
return true;
}
};