//=============Program Description==================================//
//程序文件:queeen.cpp //
//程序名称:八皇后问题 //
//方 法:非递归方法 //
//程序编写:(ExceedStudio)
//======================================================================//
#include<iostream.h>
char borad[8][8];
bool issucceed=false;
int main()
{
void fill_up();
void place(); //填写各个皇后
int check(int ,int);//检测每行,列,主副对角线上是否有Q
int x=0,y; //位置
char answer;
int i,j; //控制循环
fill_up();
k: do {
cout<<"Place place the first queen(1------8)[only in the first line!]"<<endl;
cin>>y;
if (y<=0 || y>8)
cout<<"the number is out of range!Please try again!"<<endl;
}while(y<=0 || y>8 );
borad[x][y-1]='Q';
place();
if (!issucceed)
{
cout<<"In this place can not match the order!"<<endl<<"The programme is end!"<<endl;
cout<<"Go on?(Y/N(or other))"<<endl;
cin>>answer;
if (answer=='Y' || answer=='y')
{
fill_up();
goto k;
}
}
else {
issucceed=false;
cout<<"the queen on the borad is:"<<endl;
cout<<"-------------------------"<<endl;
cout<<"Go on?(Y/N(or other))"<<endl;
cin>>answer;
if (answer=='Y' || answer=='y')
{ for (i=0;i<8;i++)
for (j=0;j<8;j++)
borad[i][j]='x';
goto k;
}
}
//检查每一个皇后的正确性(确保行列对角线上没Q)
for (i=0;i<8;i++)
for (j=0;j<8;j++)
if (borad[i][j]=='Q')
if(check(i,j))
cout<<"Wrong!"<<endl;
return 1;
}
void fill_up()
{
int i,j;
for (i=0;i<8;i++)
for (j=0;j<8;j++)
borad[i][j]='x';
}
int check(int x,int y)
{
int i,x1=x,y1=y;
for (i=0;i<8;i++)
if (borad[x][i]=='Q' || borad[i][y]=='Q')
return 0; //判断行OR列上是未有Q
//检测对角线是否有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 place()
{
int x1,x2,x3,x4,x5,x6,x7;
int i,j;
for (x1=0;x1<8;x1++)
{
if (check(1,x1))
borad[1][x1]='Q';
else
continue;
for (x2=0;x2<8;x2++)
{
if (check(2,x2))
borad[2][x2]='Q';
else
continue;
for (x3=0;x3<8;x3++)
{
if (check(3,x3))
borad[3][x3]='Q';
else
continue;
for (x4=0;x4<8;x4++)
{
if (check(4,x4))
borad[4][x4]='Q';
else
continue;
for (x5=0;x5<8;x5++)
{
if (check(5,x5))
borad[5][x5]='Q';
else
continue;
for (x6=0;x6<8;x6++)
{
if (check(6,x6))
borad[6][x6]='Q';
else
continue;
for (x7=0;x7<8;x7++)
{
if (check(7,x7))
{
borad[7][x7]='Q';
for (i=0;i<8;i++)
{
for (j=0;j<8;j++)
cout<<borad[i][j];
cout<<endl;
}
issucceed=true;
}
}
borad[6][x6]='x';
}
borad[5][x5]='x';
}
borad[4][x4]='x';
}
borad[3][x3]='x';
}
borad[2][x2]='x';
}
borad[1][x1]='x';
}
}