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.
回溯法搜索。
bool sudoku(int row, int col, int num, vector<vector<char> >& board){ //C++
if(num == 81)
return true;
int nextcol,nextrow;
if(col == 8){
nextcol = 0;
nextrow = row+1;
}else{
nextcol = col+1;
nextrow = row;
}
if(board[row][col] != '.'){
num++;
bool suc;
return sudoku(nextrow,nextcol,num,board);
}
for(int i = 1; i <=9; i++){
bool isfilled = fillcell(row,col,i,board);
bool suc;
if(isfilled){
board[row][col] = i +'0';
num++;
suc = sudoku(nextrow,nextcol,num,board);
if(suc == true)
return true;
board[row][col] = '.';
num--;
}
}
return false;
}
bool fillcell(int row, int col, int value, vector<vector<char> >& board){
char ch = value +'0';
for(int i =0; i < 9; i++)
{
if(board[row][i] == ch)
return false;
if(board[i][col] == ch)
return false;
}
int tmprow = row/3*3;
int tmpcol = col/3*3;
for(int i = tmprow; i < tmprow+3; i++)
for(int j = tmpcol; j<tmpcol+3; j++) //error
if(board[i][j] == ch)
return false;
return true;
}
void solveSudoku(vector<vector<char> > &board) {
sudoku(0,0,0,board);
}原文地址:http://blog.csdn.net/chenlei0630/article/details/42212363