/*
<p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p><p>Empty cells are indicated by the character <code>'.'</code>.</p><p>You may assume that there will be only one unique solution.</p>
*/
class Solution {
private:
bool checkValid(vector<vector<char>> board, int i, int j) {
bool flags[9] = {0};
for(int x = 0; x < 9; ++x) {
if(board[i][x] >= '1' && board[i][x] <= '9') {
if(!flags[board[i][x] - '1']) flags[board[i][x] - '1'] = true;
else return false;
}
}
memset(flags, 0 , 9);
for(int x = 0; x < 9; ++x) {
if(board[x][j] >= '1' && board[x][j] <= '9') {
if(!flags[board[x][j] - '1']) flags[board[x][j] - '1'] = true;
else return false;
}
}
memset(flags, 0, 9);
int xx = i / 3 * 3;
int yy = j / 3 * 3;
for(int x = 0; x < 3; ++x) {
for(int y = 0; y < 3; ++y) {
if(board[xx + x][yy + y] >= '1' && board[xx + x][yy + y] <= '9') {
if(!flags[board[xx + x][yy + y] - '1']) flags[board[xx + x][yy + y] - '1'] = true;
else return false;
}
}
}
return true;
}
public:
bool solveSudoku(vector<vector<char>>& board) {
int m = board.size();
int n = board[0].size();
if(n != m) return false;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
if(board[i][j] != '.')
continue;
for(char a = '1'; a <= '9'; ++a) {
board[i][j] = a; // place the number
if(checkValid(board, i, j)) {
if(solveSudoku(board)) return true;
}
board[i][j] = '.'; // if it is not good, reverse it back.
}
return false;
}
}
return true;
}
};LeetCode 37. Sudoku Solver
最新推荐文章于 2025-05-31 23:57:32 发布
本文介绍了一个使用回溯算法解决数独问题的C++程序。该程序通过递归地尝试填充空单元格来找到唯一的解决方案,并确保每行、每列及每个宫内的数字都不重复。
2991

被折叠的 条评论
为什么被折叠?



