-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueens.java
124 lines (114 loc) · 3.45 KB
/
NQueens.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package backtracking;
public class NQueens {
public static void main(String[] args) {
new NQueens().solve(4);
}
static int numSolutions;
public void solve(int n) {
numSolutions = 0;
int[][] a = new int[n][n];
backtrack(a, -1);
System.out.println("Total num of solutions: " + numSolutions);
}
private void backtrack(int[][] a, int k) {
if (isSolution(a, k)) {
processSolution(a);
numSolutions++;
} else {
k = k + 1;
int[] c = constructCandidates(a, k);
if (c != null) {
for (int i = 0; i < c.length; i++) {
makeMove(a, k, c[i]);
backtrack(a, k);
unmakeMove(a, k, c[i]);
}
}
}
}
private void makeMove(int[][] a, int k, int y) {
for (int j = 0; j < a.length; j++) {
a[k][j] += 1;
}
for (int i = 0; i < a.length; i++) {
a[i][y] += 1;
}
if (k + y < a.length) {
for (int i = 0, j = y + k; i < a.length && j > -1; i++, j--) {
a[i][j] += 1;
}
} else {
for (int j = a.length - 1, i = y + k - a.length + 1; i < a.length && j > -1; i++, j--) {
a[i][j] += 1;
}
}
if (k <= y) {
for (int i = 0, j = y - k; i < a.length && j < a.length; i++, j++) {
a[i][j] += 1;
}
} else {
for (int j = 0, i = k - y; i < a.length && j < a.length; i++, j++) {
a[i][j] += 1;
}
}
a[k][y] = 0;
}
private void unmakeMove(int[][] a, int k, int y) {
for (int j = 0; j < a.length; j++) {
a[k][j] -= 1;
}
for (int i = 0; i < a.length; i++) {
a[i][y] -= 1;
}
if (k + y < a.length) {
for (int i = 0, j = y + k; i < a.length && j > -1; i++, j--) {
a[i][j] -= 1;
}
} else {
for (int j = a.length - 1, i = y + k - a.length + 1; i < a.length && j > -1; i++, j--) {
a[i][j] -= 1;
}
}
if (k <= y) {
for (int i = 0, j = y - k; i < a.length && j < a.length; i++, j++) {
a[i][j] -= 1;
}
} else {
for (int j = 0, i = k - y; i < a.length && j < a.length; i++, j++) {
a[i][j] -= 1;
}
}
a[k][y] = 0;
}
private int[] constructCandidates(int[][] a, int k) {
// TODO optimize to exclude symmetrical duplicates
int unattacked = 0;
for (int i = 0; i < a.length; i++) {
if (a[k][i] == 0) {
unattacked++;
}
}
int[] c = null;
if (unattacked != 0) {
c = new int[unattacked];
for (int i = 0, fill = 0; i < a.length; i++) {
if (a[k][i] == 0) {
c[fill++] = i;
}
}
}
return c;
}
private void processSolution(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
System.out.print((a[i][j] <= 0 ? " #" : " _" ));
}
System.out.println();
}
System.out.println();
}
private boolean isSolution(int[][] a, int k) {
return k + 1 == a.length;
}
}