#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int ans[95][10];//定义解空间,1-92有效
int row[10];//棋盘的8行,用于存储当前可行解
int index=0;
void dfs(int current)//current表示当前处于第current行
{
if(current==8)//走到了第八行,解出来了
{
index++;//第index个解
for(int i=0;i<8;i++)
ans[index][i]=row[i];//将可行解中每行的位置存好
}
else
{
for(int i=0;i<8;i++)//第current行的8列都走一遍,看看是否可行
{
row[current]=i;int tag=1;//tag=1即不可行
for(int j=0;j<current;j++)//检查已走过的前current行,看看第i列是否可行
//有三种情况不可行:1,在current行之前,第i列已有皇后;
//2,对于当前位置(current,i),其左上和右上位置已有皇后
{
if(row[j]==i||current+row[j]==j+i||current+i==j+row[j])//j表示行,i表示列
{tag=0;break;}
}
if(tag) dfs(current+1);//第i列可行,继续扩展
}
}
}
int main()
{
int no;
while(scanf("%d",&no)!=EOF)
{
dfs(0);
for(int i=0;i<8;i++)
printf("%d",ans[no][i]+1);
printf("\n");
}
return 0;
}
【难】皇后问题,深度搜索
猜你喜欢
转载自blog.csdn.net/qq_43661234/article/details/104469295
今日推荐
周排行