# LeetCode 52. N-Queens II（N皇后）

Now, instead outputting board configurations, return the total number of distinct solutions.

public class Solution {
private int nQueens = 0;
private boolean isConflict(int[] rows, int row, int col) {
for(int i=0; i<row; i++) {
if (rows[i] == col) return true;
if (i-rows[i] == row-col) return true;
if (i+rows[i] == row+col) return true;
}
return false;
}
private void find(int[] queens, int step) {
if (step == queens.length) {
nQueens ++;
return;
}
for(int i=0; i<queens.length; i++) {
if (isConflict(queens, step, i)) continue;
queens[step] = i;
find(queens, step+1);
}
}
public int totalNQueens(int n) {
int[] queens = new int[n];
find(queens, 0);
return nQueens;
}
}

public class Solution {
private int total;
private void find(int step, int n, int col, int left, int right) {
if (step == n) {
total ++;
return;
}
int slot = col | left | right;
for(int i=0; i<n; i++) {
if (((slot >> i) & 1) != 0) continue;
int ncol = col | (1<<i);
int nleft = (left | (1<<i)) << 1;
int nright = (right | (1<<i)) >> 1;
find(step+1, n, ncol, nleft, nright);
}
}
public int totalNQueens(int n) {
find(0, n, 0, 0, 0);
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120