题目:
![](https://i-blog.csdnimg.cn/blog_migrate/d7b75ed0e4d6bf9113eb2b87a2c027f2.png)
代码(首刷看解析 2024年2月6日):
class Solution {
private:
bool backtracking(vector<vector<char>>& board) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
if (board[i][j] == '.') {
for (char k = '1'; k <= '9'; ++k) {
if (isValid(board, i, j, k)) {
board[i][j] = k;
if (backtracking(board)) return true;
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
bool isValid(vector<vector<char>>& board, int row, int col, char val) {
for (int i = 0; i < 9; ++i) {
if (board[i][col] == val || board[row][i] == val) {
return false;
}
}
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; ++i) {
for (int j = startCol; j < startCol + 3; ++j) {
if (board[i][j] == val) {
return false;
}
}
}
return true;
}
public:
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
};
代码(二刷看解析 2024年5月23日)
class Solution {
public://DFS + 剪枝
void solveSudoku(vector<vector<char>>& board) {
backtracking(board);
}
private:
bool backtracking(vector<vector<char>>& board) {
for (int i = 0; i < board.size(); i++) {
for (int j = 0; j < board[0].size(); j++) {
if (board[i][j] != '.') continue;
for (char val = '1'; val <= '9'; val++) {
if (isValid(board, i, j, val)) {
board[i][j] = val;
if (backtracking(board)) return true;
board[i][j] = '.';
}
}
return false;
}
}
return true;
}
bool isValid(const vector<vector<char>>& board, int row, int col, char val) {
// 一行重复,一列重复,所处宫内重复
for (int i = 0; i < 9; i++) {
if (board[row][i] == val) return false;
}
for (int i = 0; i < 9; i++) {
if (board[i][col] == val) return false;
}
int startRow = (row / 3) * 3, startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == val) return false;
}
}
return true;
}
};