n后问题
#include
#include
using namespace std;
class Queen {
friend int nQueen(int);
private:
bool Place(int k);
void Backtrack(int t);
int n,//皇后个数
* x;//当前解x[i]表示皇后i放在第i行第x[i]列
long sum;//当前已找到的可行方案数
};
bool Queen::Place(int k){
for(int j = 1; j < k; j++)
if ((abs(k - j) == abs(x[j] - x[k])) || (x[j] == x[k]))return false;
return true;
}
void Queen::Backtrack(int t) {
if (t > n)sum++;
else
for (auto i = 1; i <= n; i++) {
x[i] = i;
if (Place(t))Backtrack(t + 1);
}
}
int nQueen(int n) {
Queen X;
X.n = n;
X.sum = 0;
int* p = new int[n + 1];
for (auto i = 0; i <= n; i++)
p[i] = 0;
X.x = p;
X.Backtrack(1);
delete[]p;
return X.sum;
}