跟前面的N皇后问题没区别,还更简单
#include "000库函数.h" //使用回溯法
class Solution {
public:
int totalNQueens(int n) {
int res = ;
vector<int>x(n, -);//标记
NQueue(x, res, );
return res;
} void NQueue(vector<int>&x, int &num, int row) {
int n = x.size();
if (n == row)
num++;
for (int col = ; col < n; ++col)
if (Danger(x, row, col)) {
x[row] = col;
NQueue(x, num, row + );
x[row] = -;//回溯
}
} bool Danger(vector<int>x, int row, int col) {
for (int i = ; i < row; ++i)
if (col == x[i] || abs(row - i) == abs(x[i] - col))
//行列与斜边
return false;
return true;
}
}; void T052() {
Solution s;
cout << s.totalNQueens() << endl;
cout << s.totalNQueens() << endl;
}