public class Solution {
private final static Set<Integer> occupiedCols = new HashSet<Integer>();
private final static Set<Integer> occupiedDiag1s = new HashSet<Integer>();
private final static Set<Integer> occupiedDiag2s = new HashSet<Integer>();
public static int totalNQueens(int n) {
return totalNQueensHelper(0, 0, n);
}
private static int totalNQueensHelper(int row, int count, int n) {
for (int col = 0; col < n; col++) {
if (occupiedCols.contains(col)) continue;
int diag1s = row + col;
if (occupiedDiag1s.contains(diag1s)) continue;
int diag2s = row - col;
if (occupiedDiag2s.contains(diag2s)) continue;
if(row == n-1) count++;
else {
occupiedCols.add(col);
occupiedDiag1s.add(diag1s);
occupiedDiag2s.add(diag2s);
count = totalNQueensHelper(row+1, count, n);
occupiedCols.remove(col);
occupiedDiag1s.remove(diag1s);
occupiedDiag2s.remove(diag2s);
}
}
return count;
}
}
52. N-Queens II
最新推荐文章于 2021-01-22 11:28:53 发布