forked from mengli/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueensII.java
54 lines (52 loc) · 1.22 KB
/
NQueensII.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Follow up for N-Queens problem.
*
* Now, instead outputting board configurations, return the total number of distinct solutions.
*
*/
public class NQueensII {
public int solveNQueens(int n) {
if (n == 0)
return 0;
StringBuffer line = new StringBuffer();
for (int i = 0; i < n; i++) {
line.append('.');
}
StringBuffer[] sol = new StringBuffer[n];
for (int i = 0; i < n; i++) {
sol[i] = new StringBuffer(line.toString());
}
boolean[] cols = new boolean[n];
int[] row = new int[n];
int[] count = new int[1];
findSolutions(n, 0, sol, row, cols, count);
return count[0];
}
private void findSolutions(int n, int start, StringBuffer[] sol, int[] row,
boolean[] cols, int[] count) {
if (start == n) {
count[0]++;
} else {
for (int i = 0; i < n; i++) {
if (cols[i])
continue;
boolean ok = true;
for (int j = 0; j < start; j++) {
if (Math.abs(start - j) == Math.abs(i - row[j])) {
ok = false;
break;
}
}
if (ok) {
cols[i] = true;
sol[start].setCharAt(i, 'Q');
row[start] = i;
findSolutions(n, start + 1, sol, row, cols, count);
row[start] = 0;
sol[start].setCharAt(i, '.');
cols[i] = false;
}
}
}
}
}