-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueens2.java
More file actions
39 lines (36 loc) · 1.17 KB
/
NQueens2.java
File metadata and controls
39 lines (36 loc) · 1.17 KB
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
public class NQueens2 {
public int totalNQueens(int n) {
if (n == 0) {
return 0;
}
int result = 0;
int digits = (1 << n) - 1;
System.out.println("digits = " + Integer.toBinaryString(digits));
result = recur(result, digits, 0, 0, 0);
System.out.println("result = " + Integer.toBinaryString(result));
return result;
}
public int recur(int result, int digits, int row, int ld, int rd) {
if (row == digits){
result++;
System.out.println("result = " + Integer.toBinaryString(result));
return result;
}
else {
System.out.println("row = " + Integer.toBinaryString(row) + "; ld = " + Integer.toBinaryString(ld) + "; rd = " +Integer.toBinaryString(rd));
int space = digits & (~(row | ld | rd));
System.out.println("space = " + Integer.toBinaryString(space));
while (space > 0) {
int cur = space & (~space + 1);
System.out.println("cur = " + Integer.toBinaryString(cur));
space = space - cur;
System.out.println("new space = " + Integer.toBinaryString(space));
result = recur(result, digits, row + cur, (ld + cur) << 1, (rd + cur) >> 1);
}
}
return result;
}
public void test() {
System.out.println(totalNQueens(4));
}
}