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.
class Solution {
public:
bool isVaild(vector<vector<char> > &board,int a,int b){
for(int row = 0;row < 9;row ++){
if(row != a && board[a][b] == board[row][b])
return false;
}
for(int column = 0;column < 9;column ++){
if(column != b && board[a][b] == board[a][column])
return false;
}
int x = (a/3)*3 ,y = (b/3)*3;
for(int i = 0;i < 3;i ++){
for(int j = 0;j < 3;j ++){
if(x + i!= a && y + j!= b && board[a][b] == board[x + i][y + j])
return false;
}
}
return true;
}
bool generate(vector<vector<char> > &board){
for(int i = 0;i < 9;i ++){
for(int j = 0;j < 9;j ++){
if(board[i][j] == '.'){
for(int k = 1;k <= 9;k ++){
board[i][j] = k + '0';
if(isVaild(board, i, j) && generate(board))
return true;
board[i][j] = '.';
}
return false;
}
}
}
return true;
}
void solveSudoku(vector<vector<char> > &board) {
generate(board);
}
};
本文介绍了一个用于填充空格以解决数独谜题的编程算法。该算法通过验证每一行、每一列和每个九宫格内的唯一数字来确保解决方案的正确性。它从空格开始遍历,尝试填入1到9之间的数字,并递归地验证每个可能的选择,直到找到唯一的解决方案。
349

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



