bool UsedInBox(int grid[N][N], int boxStartRow, int boxStartCol,int r,int c,int num)
{
int flag=0; //to check if the number is present or not
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
if (grid[row+boxStartRow][col+boxStartCol] == num)
{
return true; // saying there is a num already in the box
}
}
}
r=r%N; // to find out the row num in that particular box which ranges from 0-2
c=c%N; // to find the col num in that partiuclar box which ranges from 0-2
int boxnum=boxStartRow/N; //to find out if it is a top most box of the grid or bottom most box or middle
if(boxnum==0)
{
for (int row = 0; row<N; row++)
{
for(int col=0;col<N;col++)
{
if(grid[row+boxnum+N][col+boxStartCol]==num)
{
flag=1; //if num is present make flag 1
if(r==row)// if row in the bottom box matches with the row in the top box
{
return false; // saying that it is valid to insert here
}
else //if num is present but rows do not match
return true;
}
}
}
if(flag==0) //if num is not present
{
return false;
}
}
else if(boxnum==N-1) //if it is a box in the last row
{
for (int row = 0; row<N; row++)
{
for(int col=0;col<N;col++)
{
if(grid[row+boxnum-N][col+boxnum-N]==num) //check for row of the num in the above box
{
flag=1;
if(r==row)
{
return false;
}
else
return true;
}
}
}
}
else //if it is a box somewhere in between
{
int flag2=0,flag3=0;
for (int row = 0; row<N; row++)
{
for(int col=0;col<N;col++)
{
if(grid[row+boxnum+N][col+boxStartCol]==num) //check for the bottom box
{
flag=1;
if(r==row)
{
flag2=1;
break;
}
else
return true;
}
}
if(flag2==1)
break;
}
if(flag==0)
{
flag2=1;
}
for (int row = 0; row<N; row++)
{
for(int col=0;col<N;col++)
{
if(grid[row+boxnum-N][col+boxnum-N]==num) //check for the top box
{
flag=1;
if(r==row)
{
flag3=1;
break;
}
else
return true;
}
}
if(flag3==1)
break;
}
if(flag2==1 && flag3==1) //if both the top box and bottom box satisy then return false
return false;
}
}