52. N皇后 II 深搜 位运算

  1. N皇后 II
    n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
    给定一个整数 n,返回 n 皇后不同的解决方案的数量。

https://leetcode-cn.com/problems/n-queens-ii/

void dfs(int n, int row, int col, int ld, int rd)n为总行数,row为当前行数,col为列,ld为左斜下,rd为右斜下
(1 << n) - 1 生成n个1,1是可以放凰后的地方
~(col | ld | rd) col和ld和rd中的1表示不能放凰后,或操作完后再取反,1表示可以凰后的地方
int bits = ~(col | ld | rd) & ((1 << n) - 1) 把这两个做与操作,现在bits表示真的可以放凰后的地方

class Solution {
public:
    int ans = 0;
    int totalNQueens(int n) {
        dfs(n, 0, 0, 0, 0);
        return ans;
    }
    void dfs(int n, int row, int col, int ld, int rd) {
        if (row >= n) {
            ans++;
            return;
        }
        int bits = ~(col | ld | rd) & ((1 << n) - 1);
        while (bits > 0) {
            int pick = bits & -bits;   //取最后一位1,其他位为0
            dfs(n , row + 1, col | pick, (ld | pick) << 1, (rd | pick) >> 1);
            bits = bits & (bits - 1);   //把最后一位变成0
        }
    }
};
原文地址:https://www.cnblogs.com/xgbt/p/13832634.html