I was solving the N Queen problem where we need to place N queens on a N X N chess board such that no two queens can attack each other.
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int size=8;
char arr[8][8];
int i,j;
void initializeBoard()
{
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
arr[i][j]='.';
}
}
}
void printArray()
{
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
printf("%c\t",arr[i][j]);
}
printf("\n");
}
printf("\n\n");
}
void placeQueen(int i,int j)
{
arr[i][j]='Q';
}
int isAvailable(int i,int j)
{
int m,n,flag;
for(m=0;m<i;m++)
{
for(n=0;n<size;n++)
{
int k=abs(i-m);
int l=abs(j-n);
if(arr[m][j]!='Q' && arr[k][l]!='Q')
{
flag=1;
}
else
{
flag=0;
break;
}
}
}
return flag;
}
int main(void)
{
initializeBoard();
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(isAvailable(i,j)==1)
{
// means that particular position is available
// and so we place the queen there
placeQueen(i,j);
break;
}
}
}
printArray();
return 0;
}
I think the problem is with the isAvailable() method. However, I am not able to find the bug. Please help me identify it.
Is the approach that i am taking involves backtracking ? If not, please provide the same with some explanations
Your approach does not backtrack. It iterates over some possibilities, not all. This problems is best solved recursively, so I wouldn’t do it as you are doing. You have to define the rules for a Queen being attacked by other. You do it using
ifs, and recursion to apply the rule again and to iterate. Most of the backtracking algorithms are written recursively.I will give you an answer, so you can base yours on mine.
The way backtracking works in the following:
n, the size of the board. The best way to search is recursively, so have in mind, the smart way to solve is using recursion.forloops just prints the board out, and checks ifQif found.# define attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j)is my rule, which asserts 2 queens are not attacking each other.forloops finds a condition which another queen can be inserted, within the constraint rules.f(n+1) = f(n) + 1for that case andf(2) = 2is my base case.