题目描述
题目难度: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代码
这段代码越看越有意思。
- 充分利用了 BitMap 的思想。
- 灵活应用位操作
- 清晰的 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);
}
}
}
}