class Solution {
public:
int ans = 0;
bool canPlace(vector<int>& Q, int y, int x) {
for(int ii = 0; ii < y; ii++) {
if(Q[ii] == x || abs(Q[ii] - x) == abs(ii - y)) return false;
}
return true;
}
void queen(vector<int>& Q, int r) {
if(r == Q.size()) {
ans++;
return ;
}
for(int ii = 0; ii < Q.size(); ii++) {
if(canPlace(Q, r, ii)) {
Q[r] = ii;
queen(Q, r + 1);
Q[r] = -1;
}
}
}
int totalNQueens(int n) {
vector<int> Q(n, -1);
queen(Q, 0);
return ans;
}
};
【leetcode 回溯(N皇后问题)C++】52. N-Queens II
猜你喜欢
转载自blog.csdn.net/m0_37454852/article/details/114333814
今日推荐
周排行