【问题】n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。给定一个整数 n,返回 n 皇后不同的解决方案的数量。
示例: 输入:
输出:
解释: 皇后问题存在如下两个不同的解法。
[
[".Q..", // 解法 1
"…Q",
"Q…",
"..Q."],
["..Q.", // 解法 2
"Q…",
"…Q",
".Q.."]
]
【思路】回溯法继续
class Solution {
public:
void solve(vector<bool>& cols_, vector<bool>& diag1s_, vector<bool>& diag2s_, int n, int row){
if(row == n){
count ++;
return;
}
for(auto col = ; col < n; col++){
int ll = row + col;
int rr = row - col + n - ;
if (cols_[col] && diag1s_[ll] && diag2s_[rr]){
cols_[col] = false;
diag1s_[ll] = false;
diag2s_[rr] = false; solve(cols_, diag1s_, diag2s_, n, row+); cols_[col] = true;
diag1s_[ll] = true;
diag2s_[rr] = true;
}
}
} int totalNQueens(int n) {
vector<bool> cols_(n, true);
vector<bool> diag1s_(*n-, true);
vector<bool> diag2s_(*n-, true);
solve(cols_, diag1s_, diag2s_, n, );
return count;
}
private:
int count = ;
};