import java.util.HashSet;
import java.util.Set;
public class NQueens {
int res = 0;
public int nQueens(int n) {
dfs(0, new HashSet<>(), new HashSet<>(), new HashSet<>(), n);
return res;
}
private void dfs(int r, Set<Integer> diagonalsSet, Set<Integer> antiDiagonalsSet, Set<Integer> colsSet, int n) {
if (r == n) {
res++;
return;
}
for (int c = 0; c < n; c++) {
int currDiagonal = r - c;
int currAntiDiagonal = r + c;
if (colsSet.contains(c) || diagonalsSet.contains(currDiagonal) || antiDiagonalsSet.contains(currAntiDiagonal)) {
continue;
}
colsSet.add(c);
diagonalsSet.add(currDiagonal);
antiDiagonalsSet.add(currAntiDiagonal);
dfs(r + 1, diagonalsSet, antiDiagonalsSet, colsSet, n);
colsSet.remove(c);
diagonalsSet.remove(currDiagonal);
antiDiagonalsSet.remove(currAntiDiagonal);
}
}
}