N皇后问题
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0Sample Output
1
92
10
题意:n皇后问题。求方案数。
搜就完事了。
谈一谈打表。询问了再去dfs并记录,不询问不记录(并不用把整张表打出来),从Lazy Tag借鉴的思路。
#include<cstdio>
#include<cstring>
int n,ans,res[15],zm[11];
bool book[15],b1[50],b2[50];
void dfs(int x,int step){ //第x行
if(step==n){
++ans;
return;
}
for(int i=1;i<=n;++i){ //第i列
if(book[i]||b1[i-x+n]||b2[i+x+n])continue;
else{
book[i]=true,b1[i-x+n]=true,b2[i+x+n]=true; //标记第i列及该斜率
res[x]=i;
dfs(x+1,step+1);
book[i]=false,b1[i-x+n]=false,b2[i+x+n]=false;
}
}
return;
}
int main(){
for(int i=1;i<=11;++i)zm[i]=-1;
while(~scanf("%d",&n)){
if(n==0)return 0;
if(zm[n]>=0){ //打表
printf("%d\n",zm[n]);
continue;
}
else {
memset(book,false,sizeof(book));
memset(b1,false,sizeof(b1));
memset(b2,false,sizeof(b2));
memset(res,0,sizeof(res));
ans=0;
dfs(1,0);
zm[n]=ans;
}
printf("%d\n",ans);
}
return 0;
}