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.
解法:
回溯法,依次每个需填写的点填入‘1_9‘并验证,行,列,对应3X3矩阵的合法性,
数独的合法:每行每列,每个小3X3中,1——9每个数字都出现且仅出现1次。
bool solvecore(vector<vector<char>> &board,int pos){
if(pos>80)
return true;
int row=pos/9;
int col=pos%9;
if(board[row][col]==‘.‘){
for(int i=1;i<=9;i++){
board[row][col]=i+‘0‘;
if(isvalid(board,pos)&&solvecore(board,pos+1)){
return true;
}
board[row][col]=‘.‘;
}
return false;
}
else
return solvecore(board,pos+1);
}
bool isvalid(vector<vector<char>> &board,int pos){
int row=pos/9;
int col=pos%9;
for(int i=0;i<9;i++){
if(board[row][i]==board[row][col]&&i!=col)
return false;
if(board[i][col]==board[row][col]&&i!=row)
return false;
}
int rs=row/3*3;
int cs=col/3*3;
for(int i=rs;i<rs+3;i++){
for(int j=cs;j<cs+3;j++){
if(board[i][j]==board[row][col]&&i!=row&&j!=col)
return false;
}
}
return true;
}
void solveSudoku(vector<vector<char>>& board) {
int rows=board.size();
if(rows!=9)
return ;
int cols=board[0].size();
if(cols!=9)
return ;
solvecore(board,0);
}
原文地址:http://searchcoding.blog.51cto.com/1335412/1694444