描述在国际象棋棋盘上放置八个皇后,要求每两个皇后之间不能直接吃掉对方。输入无输入。输出按给定顺序和格式输出所有八皇后问题的解(见Sample Output)。样例输入
样例输出
No. 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 No. 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 No. 3 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 No. 4 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 No. 5 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 No. 6 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 No. 7 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 No. 8 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 No. 9 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 ...以下省略
提示此题可使用函数递归调用的方法求解。来源计算概论05
这是八皇后问题的一种。题解:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<cstring>
using namespace std;
bool a[30],b[30],c[30],f[30][30];
int s;
void dfs(int x)
{
int r;
if(x==9)
{
s++;
printf("No. %d",s);
printf("\n");
for(int i=1;i<=8;i++)
{
printf("%d",f[i][1]);
for(int j=2;j<=8;j++)
{
printf(" %d",f[i][j]);
}
printf("\n");
}
// memset(f,0,sizeof(f));
return;
}
for(r=1;r<=8;r++)
{
if(!a[r]&&!b[x+r]&&!c[x-r+10])
{
a[r]=1;
b[x+r]=1;
c[x-r+10]=1;
f[r][x]=1;
//f[x][x+r]=1;
//f[x][x-r]=1;
dfs(x+1);
a[r]=0;
b[x+r]=0;
c[x-r+10]=0;
f[r][x]=0;
}
}
}
int main()
{
//freopen("666.in","r",stdin);
//freopen("666.out","w",stdout);
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
memset(f,0,sizeof(f));
s=0;
dfs(1);
//printf("%d\n",s);
return 0;
}
不解释原文:http://www.cnblogs.com/zclzslz127045381/p/5206261.html