Skip to content

Commit 085ab5a

Browse files
committed
add: NQueens
1 parent ac3691b commit 085ab5a

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

java/Backtracking/NQueens.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
public class NQueens {
5+
int res = 0;
6+
7+
public int nQueens(int n) {
8+
dfs(0, new HashSet<>(), new HashSet<>(), new HashSet<>(), n);
9+
return res;
10+
}
11+
12+
private void dfs(int r, Set<Integer> diagonalsSet, Set<Integer> antiDiagonalsSet, Set<Integer> colsSet, int n) {
13+
// Termination condition: If we have reached the end of the rows,
14+
// we've placed all 'n' queens.
15+
if (r == n) {
16+
res++;
17+
return;
18+
}
19+
for (int c = 0; c < n; c++) {
20+
int currDiagonal = r - c;
21+
int currAntiDiagonal = r + c;
22+
// If there are queens on the current column, diagonal or
23+
// anti-diagonal, skip this square.
24+
if (colsSet.contains(c) || diagonalsSet.contains(currDiagonal) || antiDiagonalsSet.contains(currAntiDiagonal)) {
25+
continue;
26+
}
27+
// Place the queen by marking the current column, diagonal, and
28+
// anti−diagonal as occupied.
29+
colsSet.add(c);
30+
diagonalsSet.add(currDiagonal);
31+
antiDiagonalsSet.add(currAntiDiagonal);
32+
// Recursively move to the next row to continue placing queens.
33+
dfs(r + 1, diagonalsSet, antiDiagonalsSet, colsSet, n);
34+
// Backtrack by removing the current column, diagonal, and
35+
// anti−diagonal from the hash sets.
36+
colsSet.remove(c);
37+
diagonalsSet.remove(currDiagonal);
38+
antiDiagonalsSet.remove(currAntiDiagonal);
39+
}
40+
}
41+
}

0 commit comments

Comments
 (0)