You are on page 1of 2

#include<iostream>

using namespace std;

bool soduko(int a[18][18],int n,int i,int j)


{
if(i==n-1 && j==n-1)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return true;
}
if(j==n)
{
return soduko(a,n,i+1,0);
}

if(a[i][j]!=0)
{
return soduko(a,n,i,j+1);
}
else
{
int k;
for( k=1;k<=n;k++)
{
bool c=false;
bool b=true;
//checking in row and column
for(int l=0;l<n;l++)
{
if(a[i][l]==k || a[l][j]==k)
{
b=false;
break;
}
}
//checking in small matrix
for(int k1=3*(i%3);k1<3*(i%3+1);k1++)
{
cout<<"Elements scanned: ";
for(int l=3*(j%3);l<3*(j%3+1);l++)
{
if(a[k1][l]==k)
return false;
}
cout<<endl;
}
if(!b)
{
continue;
}
else
{
a[i][j]=k;
c=soduko(a,n,i,j+1);
}
if(!c)
{continue;}
else return true;
}
if(k==n+1)
return false;
}
}

int main() {
int n;
cin>>n;

int ar[18][18];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>ar[i][j];
}
}
bool b=soduko(ar,n,0,0);
if(!b)
cout<<"-1";
return 0;
}

You might also like