Skip to content

Commit 744e7c6

Browse files
authored
Create 52. N-Queens II
1 parent ad3b7e3 commit 744e7c6

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

52. N-Queens II

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
int count;
3+
public int totalNQueens(int n) {
4+
count = 0;
5+
List<int[]> queens = new ArrayList<>();
6+
dfs(n, 0, queens);
7+
return count;
8+
}
9+
10+
private void dfs(int n, int row, List<int[]> queens) {
11+
if(queens.size() == n) {
12+
count++;
13+
return;
14+
}
15+
for(int col = 0; col < n; col++) {
16+
if(canPlaceQueen(row, col, queens)) {
17+
queens.add(new int[]{row, col});
18+
dfs(n, row+1, queens);
19+
queens.remove(queens.size()-1);
20+
}
21+
}
22+
}
23+
24+
private boolean canPlaceQueen(int row, int col, List<int[]> queens) {
25+
for(int[] q : queens) {
26+
int dx = Math.abs(q[0] - row);
27+
int dy = Math.abs(q[1] - col);
28+
if(dx == 0 || dy == 0 || dx == dy) return false;
29+
}
30+
return true;
31+
}
32+
}

0 commit comments

Comments
 (0)