leetcode -- 52. N-Queens II

题目描述

题目难度:Hard
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
在这里插入图片描述

AC代码

这段代码越看越有意思。

  1. 充分利用了 BitMap 的思想。
  2. 灵活应用位操作
  3. 清晰的 dfs
class Solution {
   int total = 0;
    public int totalNQueens(int n) {
        DFS(n,0,0,0,0);
        return total;
    }

    private void DFS(int N, int row, int col, int d1, int d2) {
        int avl = ((1 << N) - 1) & ~(col | d1 | d2);     //available positions, bitmask
        while (avl != 0) {
            int p = avl & -avl;     //取出 avl 从右往左第一个1的位置
            avl ^= p;               //相当于 avl = avl - p
            if (row == N - 1) {
               total++;
            } else {
                DFS(N, row + 1, col ^ p, (d1 ^ p) >> 1, (d2 ^ p) << 1);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值