8Queen code not working

98 views Asked by At

I have been trying to debug this code I made, it outputs only 1's in the first row of the array and all other elements are zero(from second row till the last element.), is it the problem of function calling of passing the array by value or something else. Help appreciated.

#include<stdio.h>
#include<stdlib.h>

int isSafe(int x, int y, int a[][8])
{ int i,j;

//for left check of the cols
for(i=0;i<y;i++)
{
 if(a[x][i]==1)
 return 0;
}

  //for check of left upper diagonals
  for (i = x, j = y; i >= 0 && j >= 0; i--, j--)
  {
    if(a[i][j]==1)
    return 0;
  }

   //for check of left lower diagonals
     for(i = x, j = y; i<=7 && j>=0; i++,j--)
     {
      if(a[i][j]==1)
      return 0;
     }

return 1;
}//close isSafe

int EQueen(int a[][8], int q)
{
int c=0;
  if(q==8)
  return 1;

  else
  {
  while(c<=7)
  {
    if(isSafe(q,c,a)==1)
    { 
     a[c][q] = 1;
       if(EQueen(a,q+1)==1)
       return 1;

       else
       a[c][q] = 0;

    }//close if

    c++;          
  }//close while
  return 0;

  }//close else


}//close EQueen

int main()
{
int i,j,chess[8][8] = {[0 ... 7][0 ... 7] = 0};



if(EQueen(chess,0)==1)
{

for(i=0;i<8;i++)
{
    for(j=0;j<8;j++)
    printf("%d ",chess[i][j]);

    printf("\n");
}
}

return 0;
}//close main
2

There are 2 answers

0
Cam On

I believe it is because your c variable is not incrementing. This is due to how you recursively call your EQueen function.

if(q==8)
return 1;

When your q variable is equal to 8, that specific call for that function call of EQueen will return 1. After that, all the preceding function calls of EQueen will then be true for the if statement because they will all backtrack and return the value 1 and exit that instance of the function call.

if(EQueen(a,q+1)==1)
   return 1;
else ...

This makes it so your isSafe function only looks at the 0th row (c = 0) because your c variable does not increment to check all spaces within the 2x2 dimensional array due to EQueen exiting the function before it can loop.

2
M Oehm On

Your code is good in principle. You just have to take care to use the same indexing for rows and cols throughout. The way you print the board, you use chess[row][col].

Choose a consistent nomenclature of x, i, c and so on, and you will see that you got your indexing wrong when you check the board. Change the call to IsSafe to

if (isSafe(c, q, a) == 1) ...

and it will work.

(By the way, the array is passed by reference, thus reflecting the changes you make. No problem here.)