题目链接:点这里
题目
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
思路:
可以看出同一对角线的坐标有个特点,他们的对应的坐标的和或者差的绝对值相等,因此,我们可以用几个数组来判断皇后是否处于同一对角线和同一行.
而这里我们从第一列一直往后面安排皇后,可以减少一个需要判断的数组
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> using namespace std;
bool a[30],b[30],c[30]; int an[20];
int ans,n;
void dfs(int x) { if(x==n+1) ++ans; if(x>n) return ; for(int i=1;i<=n;++i){ if(!a[i]&&!b[x+i]&&!c[x-i+n-1]){ a[i]=true; b[i+x]=true; c[x-i+n-1]=true; dfs(x+1); a[i]=false; b[i+x]=false; c[x-i+n-1]=false; } } }
int main() { for(int i=1;i<=10;++i){ n=i; ans=0; dfs(1); an[i]=ans; } while(scanf("%d",&n)!=EOF&&n){ cout<<an[n]<<endl; } return 0; }
|