good evening sir,
this code is proper run but not print anything…
please tell me what is the problem in this code i am checked 5 times with your code
// find out the starting position of sub grid use formula row=(i/sqrt(n))*sqrt(n)and column=(j/sqrt(n))sqrt(n)
// first subgrid take as a 0,1 second 0,2 … let us matrix is 33
#include
#include
using namespace std;
bool CanPlace(int mat[][9],int i,int j,int n ,int number)
{
for(int row=0;row<n;row++)
{
// row column check
if(mat[i][row]==number || mat[row][j]==number)
return false;
}
// subgrid check
//x and y starting point of sub grid
int rn=sqrt(n);
int x=(i/rn)*rn;
int y=(i/rn)*rn;
for(int row=x;row<x+rn;row++)
{
for(int column=y;column<y+rn;column++)
{
if(mat[row][column]==number)
return false;
}
}
return true;
}
bool SolveSudoku(int mat[][9],int i,int j,int n)
{
//base case
if(i==n)
{
//print matrix
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
return true;
}
// case row end
if(j==n)
{
return SolveSudoku(mat,i+1,0,n);
}
// skip the prefilled cell
if(mat[i][j]!=0)
{
return SolveSudoku(mat,i,j+1,n);
}
// rec case
// fill the current cell with possible options
for(int number=1;number<=n;number++)
{
if( CanPlace(mat,i,j,n,number))
{
//assume right answer
mat[i][j]=number;
bool couldwesolve=SolveSudoku(mat,i,j+1,n);
if(couldwesolve)
{
return true;
}
}
}
mat[i][j]=0;
return false;
}
int main()
{
int mat[9][9]={
{5,3,0,0,7,0,0,0,0},
{6,0,0,1,9,5,0,0,0},
{0,9,8,0,0,0,0,6,0},
{8,0,0,0,6,0,0,0,3},
{4,0,0,8,0,3,0,0,1},
{7,0,0,0,2,0,0,0,6},
{0,6,0,0,0,0,2,8,0},
{0,0,0,4,1,9,0,0,5},
{0,0,0,0,8,0,0,7,9}
};
SolveSudoku(mat,0,0,9);
return 0;
}