题目描述

题目难度: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.
leetcode -- 52. N-Queens II

AC代码

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);
            }
        }
    }
}

相关文章: