File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments