我自己也写了一个八皇后的程序

来源:互联网 发布:sql中in和exists 编辑:程序博客网 时间:2024/04/29 13:23
/*************************************************************************
> File Name: queen.cpp
> Author: WUBO
> Mail: 7329422@qq.com 
> Created Time: Wed Mar 18 08:09:51 2015
 ************************************************************************/


#include<iostream>
using namespace std;
int data[8][8]={0};
void show()
{
for(int x=0;x<=7;x++)
{
for(int y=0;y<=7;y++)
{
if(data[x][y])
cout<<"1 ";
else
cout<<"0 ";
}
cout<<"\n";
}




}
//打印棋盘
bool check(int x,int y)
{
if(y==0)
return true;
else
{
for(int i=0;i<y;i++)
for(int j=0;j<=7;j++)
{
if(data[i][j])
{
if(j==x)
return false;
if(x>j&&(y-i)==(x-j))
return false;
if(x<j&&(y-i)==(j-x))
return false;
}
}
}
return true;
}
//判断放下的棋子是否成功
int queen(int x,int y )
{
static int num=0;
static int line[8];//储存哪一行的queen 放在哪一列
static int t;
int z;
for(z=x;z<=7;z++)
{
data[y][z]=1;
if(y==0)
{
line[y]=z;
queen(0,y+1);
}
else if(check(z,y))
{
if(y==7)
{
show();
cout<<++num<<endl;
data[y][z]=0;
line[y]=z;
}
else
{
line[y]=z;
queen(0,y+1);


}
}
else
{
data[y][z]=0;
}
}
if(z==8)
{

y=y-1;
if(y==-1)
exit(0);
data[y][7]=0;
t=line[y];
data[y][t]=0;
x=t+1;
queen(x,y);
}
}


//递归函数


int main()
{
queen(0,0);
return 0;


}
0 0
原创粉丝点击