-
Notifications
You must be signed in to change notification settings - Fork 0
/
NQueen.java
129 lines (86 loc) · 2.75 KB
/
NQueen.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
125
126
127
128
129
package DAA;
import java.util.Scanner;
import java.util.Stack;
/*
* Created by Rebecca D'souza on 20/03/18
* */
class Queen{
int row;
int column;
int id;
Queen(int id) {
this.row = id;
this.column = 1;
this.id = id;
}
public String toString() {
return "Queen "+id+" placed at ["+row+","+column+"]";
}
}
public class NQueen{
private static Stack<Queen> stack = new Stack<>();
private static boolean noConflict(Queen queen){
for(Queen x : stack){
if(x.id<queen.id) {
System.out.println(queen + " being compared w " + x);
if (x.column == queen.column|| Math.abs(queen.row - x.row) == Math.abs(queen.column - x.column))
return false;
}
}
return true;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int filled = 1;
boolean repeat;
Queen [] queen = new Queen[N+1];
queen[1] = new Queen(1);
stack.push(queen[1]);
System.out.println("Queen "+queen[1].id+" created.");
while(filled<N){
System.out.println("FILLED : "+filled);
repeat = true;
queen[filled+1] = new Queen(filled + 1);
stack.push(queen[filled+1]);
while(repeat){
if(noConflict(stack.peek())){
System.out.println(stack.peek()+" w no conflict");
filled++;
repeat = false;
}
else if(stack.peek().column!=N){
stack.peek().column++;
System.out.println("curr column "+stack.peek().column);
if(noConflict(stack.peek())){
System.out.println(stack.peek()+" w conflict");
filled++;
repeat = false;
}
}
else if(stack.peek().column==N) {
stack.pop();
filled--;
if(stack.peek().column==N){
stack.pop();
filled--;
}
stack.peek().column++;
repeat = true;
}
}
}
System.out.println();
for (Queen x : stack)
System.out.println(x);
System.out.println();
for(int i =N;i>0;i--){
for(int j = 1;j<N+1;j++){
if(j==queen[i].column)
System.out.print("[Q]");
else System.out.print("[ ]");
}
System.out.println();
}
}
}