Description
Given N queens on an N*N chess board, find the number of ways of placing these queens so that they will not attack each other.
Input
There are multiple cases. For each case, there is only one line given the number of queens N (1<=N<=9).
Output
For each case, output the number of all possible placements of queens.
Sample Input
4
Sample Output
2
用一维数组做的x[t]=I,表示的是第T行I列放置了一个皇后,而且我们是从第一行开始放皇后的,每放完就判断放完后会不会互相攻击,如果不会就递归放下一个,直到放置的皇后数达到我们的要求,判断会不会攻击的方法也比较简单,因为我们是逐行放皇后的,所以不会存在行冲突,所以我们只需要跟前面放完的那几行判断列冲突,即x[k]==x[i],以及对角冲突abs(k-i)==abs(x[k]-x[i])这两种就好
#include <iostream>
#include <cmath>
using namespace std;
int n; //皇后个数
int sum=0; //有多少个解
int x[11]; //放置在第几列
int place(int k){
int i;
for(int i=1; i < k; ++i){
if(abs(k-i)==abs(x[k]-x[i])||x[k]==x[i]) return false;
}
return true;
}
int queen(int t){//t为放置第几个皇后
if(t>n&&n>0)//如果放置皇后超过我们需要,则该解满足,应加一
sum++;
else{
for(int i=1; i <= n; ++i){
x[t]=i;//第t个皇后放置在第i列
if(place(t)){
queen(t+1);
}
}
}
return sum;
}
int main()
{
while(cin >> n){
sum=0;
int res=queen(1);
if(n==0) cout << 0 << endl;
else cout << res << endl;
}
}