I'm trying to code a sudoku solver with recursion and backtracking. But my code always returns false. The SudokuSolver() traverses only the first row up to fourth column and then it stops and starts backtracking. The problem is that the backtracking continues until the first cell and finally returns false. As a result, none of the empty cells(cells with value "-1" ) are replaced by any other numbers(1-9) and the board remains as it is.
Compiler shows [Done] exited with code=0 in 0.557 seconds
#include<iostream>
using namespace std;
# define N 9
bool SolveSudoku();
pair<int,int> FindUnassigned();
void PrintBoard();
bool NoConflict(int, int, int);
bool inRow(int,int);
bool inCol(int, int);
bool inGrid(int, int, int);
bool isFilled(pair<int,int>);
//board[row][col]==-1 indicates an empty position
int board[N][N] = {{3,-1,6,5,-1,8,4,-1,-1},
{5,2,-1,-1,-1,-1,-1,-1,-1},
{-1,5,7,-1,-1,-1,-1,3,1},
{-1,-1,3,-1,1,-1,-1,8,-1},
{9,-1,-1,8,6,3,-1,-1,5},
{-1,5,-1,-1,9,-1,6,-1,-1},
{1,3,-1,-1,-1,-1,2,5,-1},
{-1,-1,-1,-1,-1,-1,-1,7,4},
{-1,-1,5,2,-1,6,3,-1,-1}};
int main() {
if(SolveSudoku())
PrintBoard();
return 0;
}
bool SolveSudoku() {
pair<int,int> pos = FindUnassigned();
int row=pos.first;
int col=pos.second;
if(isFilled(pos)) { return true; }
for(int num=1; num<=9; num++) {
if(NoConflict(num,row,col)) {
board[row][col]=num;
SolveSudoku();
board[row][col]=-1;
}
}
return false;
}
pair<int,int> FindUnassigned() {
pair<int,int> pos;
pos.first=-1;
pos.second=-1;
for(int r=0; r<N; r++) {
for(int c=0; c<N; c++) {
if(board[r][c]==-1) {
pos.first=r;
pos.second=c;
return pos;
}
}
}
return pos;
}
bool isFilled(pair<int,int> pos) {
return (pos.first==-1 && pos.second==-1);
}
bool NoConflict(int num, int r, int c) {
return ((!inRow(numenter code here,r)==false) && (!inCol(num,c)==false) && (!inGrid(num,r-r%3,c-c%3)==false));
}
bool inRow(int num, int r) {
for(int c=0; c<N; c++) {
if(board[r][c]==num) return true;
}
return false;
}
bool inCol(int num, int c) {
for(int r=0; r<N; r++) {
if(board[r][c]==num) return true;
}
return false;
}
bool inGrid(int num, int rf, int cf) {
for(int r=0; r<3; r++) {
for(int c=0; c<3; c++) {
if(board[r+rf][c+cf]==num) return true;
}
}
return false;
}
void PrintBoard() {
for(int r=0; r<N; r++) {
for(int c=0; c<N; c++) {
cout<<board[r][c]<<"\t";
}
enter code here cout<<endl;
}
}