N皇后问题
Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1 8 5 0
Sample Output
1 92 10
代码如下:
#include <cstdio>
#include <cstring>
const int maxn = 15;
int board[maxn];
int ans,n;
int res[maxn];
void dfs(int x)
{
if(x == n ){
ans++;
}else{
for(int i = 0;i < n;i++){
int ok = 1;
board[x] = i;
for(int j = 0;j < x;j++){
//当前布局不合法
if(board[x] == board[j] || x - board[x] == j - board[j] || x + board[x] == j + board[j]){
ok = 0;
break;
}
}
if(ok)
dfs(x + 1);
}
}
}
int main()
{
while(scanf("%d",&n) != EOF && n){
ans = 0;
if(res[n] == 0){
dfs(0);
res[n] = ans;
printf("%d\n",ans);
}else{
printf("%d\n",res[n]);
}
}
return 0;
}