#include<iostream.h>
class QUEEN
{
public:
QUEEN(int x=0,int y=0);
void fill_up();
void printf();
int check(int x,int y);
void place(int n);
virtual ~QUEEN();
private:
int loc_x;
int loc_y;
char borad[8][8];
};
QUEEN::QUEEN(int x,int y)
{
loc_x=x;
loc_y=y;
fill_up();
borad[loc_x][loc_y]='Q';
}
void QUEEN::fill_up()
{
int i,j;
for (i=0;i<8;i++)
for (j=0;j<8;j++)
borad[i][j]='x';
return;
}
void QUEEN::printf()
{
int i,j;
for (i=0;i<8;i++)
{ for (j=0;j<8;j++)
cout<<borad[i][j];
cout<<endl;
}
return;
}
int QUEEN::check(int x,int y)
{
int x1=x,y1=y;
int i;
for (i=0;i<8;i++)
if (borad[x][i]=='Q' || borad[i][y]=='Q')
return 0; //判断行OR列上是未有Q
while (x1<8 && y1<8)
{
if (borad[x1+1][y1+1]=='Q' )
return 0;
else {
x1++;
y1++;
}
}
x1=x;
y1=y;
while (x1>0 && y1>0)
{
if (borad[x1-1][y1-1]=='Q' )
return 0;
else {
x1--;
y1--;
}
}
x1=x;
y1=y;
while (x1>0 && y1<8)
{
if (borad[x1-1][y1+1]=='Q' )
return 0;
else {
x1--;
y1++;
}
}
x1=x;
y1=y;
while (x1<8 && y1>0)
{
if (borad[x1+1][y1-1]=='Q' )
return 0;
else {
x1++;
y1--;
}
}
return 1;
}
void QUEEN::place(int n)
{
int i;
for (i=0;i<8;i++) //控制每一行皇后的位置(列数)
{
if (check(n,i)) //以皇后数控制行数~~~~检测此行的每一列是否可以放上Q
{
borad[n][i]='Q';
if (n<7)
place(n+1); //当少于8个皇后时,则递归下一个!
else {
printf(); //否则输出结果
return;
}
borad[n][i]='x'; //当最外的for控制着列位置,当这个位置的Q,
//使得后面排不到8个,这时就要放Q于下一位
}
}
}
QUEEN::~QUEEN()
{
cout<<"GoodBye!"<<endl;
}
int main()
{
QUEEN equeen(0,0);
equeen.place(1);
return 0;
}