这道题有需要将结果存储在一个单独的数组res里,再在每次题目输入n时从res数组中取出结果,否则会超时。
#include<iostream>
using namespace std;
const int N = 30;
int n;
bool dg[N],udg[N];
bool col[N];
int cnt;
int res[15];
void dfs(int u){
if(u == n){
cnt++;
return;
}
// 从第一行开始看这个皇后可以放在哪一列
for(int i = 1; i <= n; i++){
if(!col[i] && !dg[u+i] && !udg[i-u+n]){
col[i] = dg[u+i] = udg[i-u+n] = true;
dfs(u+1);
col[i] = dg[u+i] = udg[i-u+n] = false;
}
}
}
int main(){
for(int i = 1; i <= 10; i++){
n = i;
dfs(0);
res[i] = cnt;
cnt = 0;
}
while(cin >> n && n) cout << res[n] << endl;
return 0;
}
原文:https://www.cnblogs.com/ApStar/p/14646947.html