-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNQueen.java
87 lines (71 loc) · 1.32 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
import java.util.Scanner;
class Queen {
int a[][] = new int[10][10];
int n, i,c,f,m;
Queen()
{
m=1;
}
void input() {
Scanner s = new Scanner(System.in);
System.out.println("Enter n:");
n = s.nextInt();
}
int condition(int i, int j, int n) {
int k, l;
for (int z = 0; ++c>0&&z <= i - 1; z++) {
if (a[z][j] == 1)
return 0;
}
for (k = i - 1, l = j - 1; ++c>0&&k >= 0 && l >= 0; k = k - 1, l = l - 1) {
if (a[k][l] == 1)
return 0;
}
for (k = i - 1, l = j + 1;++c>0&& k >= 0 && l <= n; k = k - 1, l = l + 1) {
if (a[k][l] == 1)
return 0;
}
return 1;
}
void logic() {
if (i == n && n!=1) {
System.out.println("the possible solution:"+m);
m++;
print();
f=1;
}
int v=0;
for (int j = 0; j < n; j++) {
if (condition(i, j, n) == 1) {
a[i][j] = 1;
v=j;
i = i + 1;
logic();
i = i - 1;
a[i][v] = 0;
}
}
}
void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
{
if(a[i][j]==1)
System.out.print(" "+"Q");
else
System.out.print(" "+"-");
}
System.out.println();
}
System.out.println();
}
}
class Main {
public static void main(String args[]) {
Queen q = new Queen();
q.input();
q.logic();
if (q.f==0)
System.out.println("no");
}
}