forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueensII.java
More file actions
35 lines (31 loc) · 779 Bytes
/
NQueensII.java
File metadata and controls
35 lines (31 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class NQueensII {
private int total;
public int totalNQueens(int n) {
int[] f = new int[n];
dfs(f, 0);
return total;
}
private void dfs(int[] f, int row) {
if (row == f.length) {
total++;
return;
}
for (int j = 0; j < f.length; j++) {
if (isValid(f, row, j)) {
f[row] = j;
dfs(f, row + 1);
}
}
}
private boolean isValid(int[] f, int row, int col) {
for (int i = 0; i < row; i++) {
if (f[i] == col) {
return false;
}
if (Math.abs(i - row) == Math.abs(f[i] - col)) {
return false;
}
}
return true;
}
}