版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/88725990
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int check[3][25], n=10, sum=0;
int ans[15];
void dfs(int line)
{
if (line>n){
sum++;
return;
}
for (int j=1; j<=n; j++){
if (check[0][j]==0 && check[1][line+j]==0 && check[2][line-j+n]==0){
check[0][j]=1;
check[1][line+j]=1;
check[2][line-j+n]=1;
dfs(line+1);
check[0][j]=0;
check[1][line+j]=0;
check[2][line-j+n]=0;
}
}
}
int main()
{
for (n=1; n<=10; n++){
sum=0;
dfs(1);
ans[n]=sum;
}
while (scanf("%d", &n) && n){
printf("%d\n", ans[n]);
}
return 0;
}