题目: biubiu
题意:和力扣51一样,但是要求的结果不一样,力扣51要求把棋盘打印出来,52要求共有多少种情况。
根据题解提供的思路,使用位运算,通过使用数字的二进制码来对棋盘进行标记,通过左移右移来确定皇后的位置,二进制码为1表示该位置可以放置皇后。
大佬代码:
class Solution {
public:
int totalNQueens(int n) {
dfs(n, 0, 0, 0, 0);
return this->res;
}
void dfs(int n, int row, int col, int ld, int rd) {
if (row >= n) {
res++; return; }
// 将所有能放置 Q 的位置由 0 变成 1,以便进行后续的位遍历
int bits = ~(col | ld | rd) & ((1 << n) - 1);
//cout << "^^^^^^^" << row << endl;
//cout << col << " " << ld << " " << rd << " " << ~(col | ld | rd)<<" "<< bits << endl;
while (bits > 0) {
int pick = bits & -bits; // 注: x & -x
//cout << "*****" << bits <<" "<<-bits<<" "<<pick << endl;
dfs(n, row + 1, col | pick, (ld | pick) << 1, (rd | pick) >> 1);
//cout << "######" << bits << endl;
bits &= bits - 1; // 注: x & (x - 1)
//cout << "#####" << bits << endl;
}
}
private:
int res = 0;
};
int main() {
int n;
while (cin >> n) {
Solution s;
cout << s.totalNQueens(n) << endl;
}
return 0;
}