69 lines
963 B
C++
69 lines
963 B
C++
|
This program finds the locations of placing n queens in a n*n chessboard
|
||
|
so that none attack any other
|
||
|
|
||
|
Code :
|
||
|
#include<iostream.h>
|
||
|
#include<conio.h>
|
||
|
#include<math.h>
|
||
|
#include<process.h>
|
||
|
#include<graphics.h>
|
||
|
class queen
|
||
|
{ int n,x[100];
|
||
|
public:
|
||
|
queen();
|
||
|
void nqueen(int,int);
|
||
|
int place(int,int);
|
||
|
};
|
||
|
queen::queen()
|
||
|
{
|
||
|
int k=1;
|
||
|
textcolor(GREEN);
|
||
|
cprintf("
|
||
|
Enter the number of queens:");
|
||
|
cin>>n;
|
||
|
nqueen( k, n);
|
||
|
}
|
||
|
void queen::nqueen(int k,int n)
|
||
|
{
|
||
|
for(int i=1;i<=n;i++)
|
||
|
{
|
||
|
if(place(k,i))
|
||
|
{
|
||
|
x[k]=i;
|
||
|
clrscr();
|
||
|
if(k==n)
|
||
|
{
|
||
|
for(int j=1;j<=n;j++)
|
||
|
{textcolor(x[j]);
|
||
|
gotoxy(1,j);
|
||
|
cprintf("
|
||
|
queen %d : %d",j,x[j]);
|
||
|
}
|
||
|
getch();
|
||
|
|
||
|
break;
|
||
|
}
|
||
|
else
|
||
|
nqueen(k+1,n);
|
||
|
}
|
||
|
}
|
||
|
return;
|
||
|
}
|
||
|
int queen::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;
|
||
|
}
|
||
|
void main()
|
||
|
{
|
||
|
clrscr();
|
||
|
queen q;
|
||
|
}
|
||
|
|
||
|
|