//program to solve eightqueens problem using backtracking technique
#include <iostream.h>
#include<conio.h>
class eightqueen
{
private:
int row[8],s;
int safe(int,int);
void putboard();
public:
eightqueen()
{
s=0;
}
void queen(int);
};
int eightqueen::safe(int x, int y)
{
int i;
for(i=1;i<=y;i++)
if( row[y-i]==x || row[y-i]==x-i || row[y-i]==x+i)
return 0;
return 1;
}
void eightqueen::putboard()
{
int x,y;
cout<<"\nSolution #"<<++s<<":\n---------------------------------\n";
for(y=0;y<8; y++)
{
for (x=0;x<8;x++)
if(x==row[y])
cout<<"| Q ";
else
cout<<"| ";
cout<<"|\n---------------------------------\n";
}
getch();
}
void eightqueen::queen(int y)
{
int x;
for(x=0;x<8;x++)
{
row[y-1]=x;
if( safe(x,y-1) )
if (y<8)
queen(y+1);
else
putboard();
}
}
void main()
{
eightqueen eq;
clrscr();
eq.queen(1);
}