Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
具体解析见http://www.matrix67.com/blog/archives/266
Runtime: 2 ms beats 88.86% of java submissions.
private int sum = 0;
private long MASK;
public int totalNQueens(int n) {
MASK = (1 << n) - 1;
dfs(0L, 0L, 0L);
return sum;
}
private void dfs(long col, long left, long right) {
if (col == MASK) {//col==MASK的时候证明n个皇后都放进去了
sum++;
return;
}
long status = ~(col | left | right) & MASK;//三个并起来,得到该行所有的禁位,取反后就得到所有可以放的位置
while (status > 0) {
long pos = status & -status;//取出status最右的1位
status -= pos;
dfs(col | pos, (left | pos) << 1, (right | pos) >> 1);
}
return;
}