Problem Description
在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。
你的任务是,对于给定的N,求出有多少种合法的放置方法。
Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1
8
5
0
Sample Output
1
92
10
Author
cgf
Source
2008 HZNU Programming Contest
思路
普通的N皇后问题。
时间复杂度很狗。
本蒟蒻用了不讲狗德的打表(自己编的程序算出解在打表)。
主要是TLE了。
他的时间卡的很死。
其实可以在程序的开头把1 - 10 的情况都写出来。
AC代码
#include <iostream>
#include <cmath>
using namespace std;
int n, ans;
int x[20];
bool check(int tmp) {
for (int i = 1; i < tmp; i++) {
if ((x[tmp] == x[i]) || (tmp - i == abs(x[tmp] - x[i]))) return false;
}
return true;
}
void dfs(int step) {
if (step > n) {
ans++;
} else {
for (int i = 1; i <= n; i++) {
x[step] = i;
if (check(step)) {
dfs(step + 1);
}
}
}
}
int main() {
while (1) {
ans = 0;
cin >> n;
if (!n) break;
dfs(1);
cout << ans << endl;
}
return 0;
}
打表
#include <iostream>
#include <cmath>
using namespace std;
int n, ans;
int x[20] = {0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724};
int main() {
while (1) {
ans = 0;
cin >> n;
if (!n) break;
cout << x[n] << endl;
}
return 0;
}
整合代码
#include <iostream>
#include <cmath>
using namespace std;
int n, ans;
int x[20], ans[20];
bool check(int tmp) {
for (int i = 1; i < tmp; i++) {
if ((x[tmp] == x[i]) || (tmp - i == abs(x[tmp] - x[i]))) return false;
}
return true;
}
void dfs(int step) {
if (step > n) {
ans++;
} else {
for (int i = 1; i <= n; i++) {
x[step] = i;
if (check(step)) {
dfs(step + 1);
}
}
}
}
int main() {
for (int i = 1; i <= 10; i++) {
ans[i] = dfs(i);
}
while (1) {
ans = 0;
cin >> n;
if (!n) break;
cout << ans[n] << endl;
}
return 0;
}