12. Design and implement C/C++ Program for N Queen's problem using Backtracking.
Algorithm:
/* outputs all possible acceptable positions of n queens on n x n chessboard */
// Initialize x [ ] to zero
// Set k = 1 start with first queen
Repeat for i = 1 to n // try all columns one by one for kth queen
if Place (k, i) true then
{
x(k) = i // place kth queen in column i
if (k=n)
all queens placed and hence print output (x[ ])
else
NQueens(K+1,n) //try for next queen
}
Place (k,i)
/* finds if kth queen in kth row can be placed in column i or not; returns true if queen can be
placed */
// x[1,2, . . . k-1] have been defined
//queens at (p, q) & (r, s) attack if |p-r| = |q-s|
Repeat for j = 1 to (k-1)
if any earlier jth queen is in ith column ( x[j]= i)
or in same diagonal ( abs(x[ j] - i) = abs( j - k) )
then kth queen cannot be placed (return false)
return true (as all positions checked and no objection)
Program:
#include <stdio.h>
int count=0,x[5];
int main()
{
int n;
printf("\n enter the number of queen");
scanf("%d",&n);
nqueen(1,n);
if(count==0)
printf("\n no solution found");
else
printf("\n number of solution found is:%d",count);
return 0;
}
int place(int k,int i)
{
int j; for(j=1;j<k;j++)
if((x[j]==i)||(abs(x[j]-i)==abs(j-k)))
return 0;
return 1;
}
nqueen(int k,int n)
{
int i,j,p; for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
{
count++;
printf("solution=%d",count); printf("\n"); for(j=1;j<=n;j++)
{
for(p=1;p<=n;p++)
if(x[j]==p)
printf("$\t");
else
printf("0\t");
printf("\n");
}
printf("\n");
}
else
nqueen(k+1,n);
}
}
return 0;
}