forked from xtaci/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEightQueen.java
More file actions
79 lines (68 loc) · 1.32 KB
/
Copy pathEightQueen.java
File metadata and controls
79 lines (68 loc) · 1.32 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
public class EightQueen {
private final int COUNT = 8;
private int [][] matrix;
private int numOfResult = 0;
public EightQueen(){
matrix = new int[8][8];
numOfResult = 0;
}
private void printResult() {
numOfResult++;
System.out.println("Result " + numOfResult + " :");
printArray();
}
private void printArray(){
System.out.println("**********************");
for (int i = 0; i < COUNT; i++) {
for (int j = 0; j < COUNT; j++) {
System.out.print(matrix[i][j]);
}
System.out.println("");
}
System.out.println("**********************");
}
private boolean check(int row, int col) {
int i, j;
// can not be the same column
i = row - 1;
while (i >=0) {
if(matrix[i][col] == 1) {
return false;
}
i--;
}
// can not be the same diagnal
i = row - 1;
j = col - 1;
while (i >= 0 && j >= 0) {
if (matrix[i][j] == 1) {
return false;
}
i--;
j--;
}
i = row - 1;
j = col + 1;
while (i >= 0 && j < COUNT) {
if (matrix[i][j] == 1) {
return false;
}
i--;
j++;
}
return true;
}
public void solve(int row) {
for(int i = 0; i <COUNT; i++){// try on all columns
matrix[row][i] = 1;
if (check(row, i)) {
if (row == COUNT - 1) {
printResult();
} else {
solve(row+1);
}
}
matrix[row][i] = 0;//roll back
}
}
}