力扣52.N皇后II

题目: 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赟家小菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值