Problem
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.
Code
void sudokuTable(vector<vector<char> > &board,vector<vector<bool> > &p)
{
for(int i =0;i < 9; ++i){
for(int j =0;j < 9; ++j){
if(board[i][j] != '.')
p[i][j] = true;
}
}
}
bool getNextCell(vector<vector<char> > &board,vector<vector<bool> > &p,
int i,int j,int &a,int &b,bool &completed){
for(int k = j;k < 9; ++k){
if(!p[i][k]){
a = i;
b = k;
return true;
}
}
for(int l = i + 1;l < 9; ++l){
for(int k = 0;k < 9; ++k){
if(!p[l][k]){
a = l;
b = k;
return true;
}
}
}
completed = true;
return false;
}
vector<char> getNumbers(vector<vector<char> > &board,vector<vector<bool> > &p,int i,int j){
vector<char> result;
for(int num = 0;num < 9;++num){
char ch = '1' + num;
bool found = false;
//check row
for(int k = 0;k < j; ++k){
if(board[i][k] == ch){
found = true;
break;
}
}
if(found)
continue;
//check row
for(int k = j + 1;k < 9; ++k){
if(p[i][k] && board[i][k] == ch){
found = true;
break;
}
}
if(found)
continue;
//check col
for(int k = 0;k < i; ++k){
if(board[k][j] == ch){
found = true;
break;
}
}
if(found)
continue;
//check col
for(int k = i + 1;k < 9; ++k){
if(p[k][j] && board[k][j] == ch){
found = true;
break;
}
}
if(found)
continue;
//check block
int blockrow = i - (i % 3);
int blockcol = j - (j % 3);
for(int k = blockrow;k < i; ++k){
for(int l = blockcol;l < j; ++l){
if(board[k][l] == ch){
found = true;
break;
}
}
if(found)
break;
}
if(found)
continue;
for(int k = i + 1;k < (blockrow + 3); ++k){
for(int l = blockcol;l < (blockcol + 3); ++l){
if(p[k][l] && board[k][l] == ch){
found = true;
break;
}
}
if(found)
break;
}
if(found)
continue;
for(int k = j + 1;k < (blockcol + 3); ++k){
for(int l = blockrow;l < (blockrow + 3); ++l){
if( l < i ){
if(board[l][k] == ch){
found = true;
break;
}
}
else{
if(p[l][k] && board[l][k] == ch){
found = true;
break;
}
}
}
if(found)
break;
}
if(found)
continue;
result.push_back(ch);
}
return result;
}
void solveSudoku_r(vector<vector<char> > &board,vector<vector<bool> > &p,
int i,int j,bool &completed){
vector<char> numbers = getNumbers(board,p,i,j);
int sz = numbers.size();
for(int k = 0;k < sz; ++k){
board[i][j] = numbers[k];
int a,b;
if(!getNextCell(board,p,i,j + 1,a,b,completed))
return;
solveSudoku_r(board,p,a,b,completed);
if(completed)
break;
}
}
void solveSudoku(vector<vector<char> > &board) {
vector<vector<bool> > p(9,vector<bool>(9,false));
sudokuTable(board,p);
int a,b;
bool completed = false;
getNextCell(board,p,0,0,a,b,completed);
solveSudoku_r(board,p,a,b,completed);
}