- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNQueen.java
More file actions
Latest commit
79 lines (68 loc) · 2.24 KB
/
Copy pathNQueen.java
File metadata and controls
79 lines (68 loc) · 2.24 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
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.LinkedList;
publicclassNQueen {
privatestaticintN;
privatestaticbooleancol[];
privatestaticbooleandiagonal1[];
privatestaticbooleandiagonal2[];
privatestaticLinkedList<Point> points;
staticclassPoint {
privateintx;
privateinty;
publicPoint(intx, inty) {
this.x = x;
this.y = y;
}
}
publicstaticbooleannQueenHelper(intn) {
returnnQueen(n, 0);
}
publicstaticbooleannQueen(intn, intdepth) {
if (depth == n) {
returntrue;
}
// Back Tracking
for (inti = 0; i < n; i++) {
if (!col[i] && !diagonal1[depth - i + n-1] && !diagonal2[depth + i]) {
col[i] = true;
diagonal1[depth - i + n-1] = true;
diagonal2[depth+i] = true;
points.add(newPoint(depth, i));
booleantruth = nQueen(n, depth+1);
if (truth)
returntrue;
col[i] = false;
diagonal1[depth - i + n-1] = false;
diagonal2[depth+i] = false;
points.remove();
}
}
returnfalse;
}
publicstaticvoidmain(String[] args) throwsIOException {
BufferedReaderbr = newBufferedReader(newInputStreamReader(System.in));
System.out.print("Please enter the number N : ");
N = Integer.parseInt(br.readLine());
col = newboolean[N];
diagonal1 = newboolean[N*2-1];
diagonal2 = newboolean[N*2-1];
points = newLinkedList<>();
//Output:
// N Queen exist on 4 x 4 Matrix
// points:
// 0 1
// 1 3
// 2 0
// 3 2
if (nQueenHelper(N)) {
System.out.println("\n" + "N Queen Exist on " + N + " x " + N + " Matrix" + "\n");
System.out.println("points:");
for (Pointpoint : points)
System.out.println(point.x + ", " + point.y);
} else {
System.out.println("N Queen doesn't exist on " + N + " x " + N + " Matrix" + "\n");
}
}
}