Skip to content

Commit e799f74

Browse files
52. N-Queens II (java)
1 parent dbec940 commit e799f74

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
3+
int count = 0;
4+
5+
public int totalNQueens(int n) {
6+
int[] c = new int[n];
7+
search(0, n, c);
8+
return count;
9+
}
10+
11+
public void search(int cur, int n, int[] c) {
12+
if (cur == n) {
13+
count++;
14+
return;
15+
}
16+
17+
for (int i = 0; i < n; i++) {
18+
boolean flag = true;
19+
c[cur] = i;
20+
for (int j = 0; j < cur; j++) {
21+
if ((c[cur] == c[j]) || ((c[cur] - cur) == (c[j] - j)) || ((c[cur] + cur) == (c[j] + j))) {
22+
flag = false;
23+
break;
24+
}
25+
}
26+
if (flag) search(cur + 1, n, c);
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)