forked from hoohack/CodeInJavaNotes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightQueen.java
More file actions
83 lines (70 loc) · 2.03 KB
/
EightQueen.java
File metadata and controls
83 lines (70 loc) · 2.03 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
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
package chapter5;
public class EightQueen {
private int[] queenRow;
private static int INITIAL = -9999;
private void setMap(int size) {
queenRow = new int[size];
for (int i = 0; i < size; i++) {
queenRow[i] = INITIAL;
}
}
public boolean valid(int row, int col) {
for (int i = 0; i < queenRow.length; ++i) {
if (queenRow[i] == col || Math.abs(i - row) == Math.abs(queenRow[i] - col))
return false;
}
return true;
}
public void print() {
int i, j;
for (i = 0; i < queenRow.length; ++i) {
for (j = 0; j < queenRow.length; ++j) {
if (queenRow[i] != j)
System.out.print(". ");
else
System.out.print("# ");
}
System.out.println();
}
System.out.println();
System.out.println("--------------------------------");
}
public void find() {
int n = 0;
int i = 0, j = 0;
while (i < queenRow.length) {
while (j < queenRow.length) {
if(valid(i, j)) {
queenRow[i] = j;
j = 0;
break;
} else {
++j;
}
}
if(queenRow[i] == INITIAL) {
if (i == 0) {
break;
} else {
--i;
j = queenRow[i] + 1;
queenRow[i] = INITIAL;
continue;
}
}
if (i == queenRow.length - 1) {
System.out.printf("answer %d : \n", ++n);
print();
j = queenRow[i] + 1;
queenRow[i] = INITIAL;
continue;
}
++i;
}
}
public static void main(String[] args) {
EightQueen eightQueen = new EightQueen();
eightQueen.setMap(8);
eightQueen.find();
}
}