N皇后问题
Description
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
Output
Sample Input
Sample Output
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
const int N = 12;
int area[12];
int ans;
int n;
void DFS(int m) {
if (m == n) {
ans++;
return ;
}
for (int i = 0; i < n; i++) {
area[m] = i;
bool ok = true;
for (int j = 0; j < m; j++) {
if (area[m] == area[j] || (m - area[m]) == (j - area[j]) || (m + area[m]) == (j + area[j])) {
ok = false;
break;
}
}
if (ok) DFS(m + 1);
}
}
int main() {
int rec[11];
for (int i = 1; i <= 10; i++) {
memset(area, 0, sizeof(area));
ans = 0;
n = i;
DFS(0);
rec[i] = ans;
}
while (cin>>n) {
if (!n) break;
cout<<rec[n]<<endl;
}
return 0;
}