N Queen Problem > C Program
To implement NQueen Problem > C Program
Analysis of Algorithm, Artificial Intelligence
Program:#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
int *x;
int place(int k,int i)
{
int j;
for(j=1;j<=k-1;j++)
{
if(x[j]==i||abs(x[j]-i)==abs(j-k))
return 0;
}
return 1;
}
void nQueen(int k,int n)
{
int i;
for(i=1;i<=n;i++)
{
if(place(k,i))
{
x[k]=i;
if(k==n)
{
printf("\n");
for(i=1;i<=n;i++)
printf("%d\t",x[i]);
}
else
nQueen(k+1,n);
}
}
}
void main()
{
int n;
clrscr();
printf("Enter the number of queens(n):");
scanf("%d",&n);
x=(int *)malloc((n+1)*sizeof(int));
printf("The possible placements are:");
nQueen(1,n);
getch();
}
/*
Enter the number of queens(n):5
The possible placements are:
1 3 5 2 4
1 4 2 5 3
2 4 1 3 5
2 5 3 1 4
3 1 4 2 5
3 5 2 4 1
4 1 3 5 2
4 2 5 3 1
5 2 4 1 3
5 3 1 4 2
*/
Comments
Post a Comment