solveSudoku
function is called from main()
function.
I have written the following function for solving sudoku :
bool isFull(vector<vector<char>>& board){
for(int i = 0 ; i < board.size(); i++){
for(int j = 0 ; j < board[0].size(); j++){
if(board[i][j] == '.') return false;
}
}
return true;
}
vector<int> poss(vector<vector<char>>& board, int x, int y){
vector<int> ans;
set<int> s;
//check across columns
for(int j = 0 ; j < board[0].size(); j++){
if(board[x][j]!='.') s.insert(board[x][j] -'0');
}
//check acroos rows
for(int i = 0 ; i < board.size(); i++){
if(board[i][y]!='.') s.insert(board[i][y] - '0');
}
//check in square
int r, c;
if(x>=0 && x<=2) r = 0;
if(x>=3 && x<=5) r = 3;
if(x>=6 && x<=8) r = 6;
if(y>=0 && y<=2) c = 0;
if(y>=3 && y<=5) c = 3;
if(y>=6 && y<=8) c = 6;
for(int i = r; i <= r + 2; i++){
for(int j = c; j <= c + 2; j++){
if(board[i][j]!='.') s.insert(board[i][j]-'0');
}
}
for(int n = 1; n <=9 ; n++){
if(s.find(n) == s.end()){
ans.push_back(n);
}
}
return ans;
}
vector<int> Fempty(vector<vector<char>>& board){
vector<int> ans;
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[0].size(); j++){
if(board[i][j] == '.'){
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
}
return ans;
}
void solveSudoku(vector<vector<char>>& board) {
if(isFull(board)) return;
//not full
//Fempty returns first empty cell coordinate
vector<int> empty = Fempty(board);
int xe = empty[0], ye = empty[1];
//poss returns the vector of possible values
vector<int> pos = poss(board, xe, ye);
if(!pos.empty()){
for(int i = 0; i < pos.size(); i++){
board[xe][ye] = pos[i] + '0';
solveSudoku(board);
}}
board[xe][ye] = '.';
return;
}
Input sudoku is given as argument when solveSudoku
is called in the main()
function. It consists of characters from 1
to 9
and .
which represents empty character. solveSudoku
function's job is to fill all the elements in sudoku correctly(change values in board
in place).
When I run this program my output shows no change.
If I comment out board[xe][ye] = '.'
, my output shows some changes but it remains same after a cell runs out of possible values.
Edit : It is known that board
has a solution.
What I am doing wrong?