public class Solution {
Set<Integer> rowSet = new HashSet<Integer>();
Set<Integer> diag1Set = new HashSet<Integer>();
Set<Integer> diag2Set = new HashSet<Integer>();
public int totalNQueens(int n) {
return dfs(0, 0, n);
}
private int dfs(int col, int count, int n) {
for (int row = 0; row < n; row++) {
if (rowSet.contains(row)) continue;
int diag1 = col - row;
if (diag1Set.contains(diag1)) continue;
int diag2 = col + row;
if (diag2Set.contains(diag2)) continue;
if (col == n - 1) {
count++;
} else {
rowSet.add(row);
diag1Set.add(diag1);
diag2Set.add(diag2);
count = dfs(col + 1, count, n);
rowSet.remove(row);
diag1Set.remove(diag1);
diag2Set.remove(diag2);
}
}
return count;
}
}