-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.java
More file actions
53 lines (48 loc) · 1.38 KB
/
NQueen.java
File metadata and controls
53 lines (48 loc) · 1.38 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
import java.util.Scanner;
public class NQueen {
public static int[] x = new int[10];
public static int solutionNumber = 0;
public static void printboard(int n) {
int i;
for (i = 1; i <= n; i++) {
System.out.print(x[i] + " ");
}
System.out.println();
}
public static void NQueen(int k, int n) {
int i;
for (i = 1; i <= n; i++) {
if (place(k, i) == 1) {
x[k] = i;
if (k == n) {
solutionNumber++;
System.out.println("Solution Number: " + solutionNumber);
printboard(n);
} else {
NQueen(k + 1, n);
}
}
}
}
public static int place(int k, int i) {
int j;
for (j = 1; j < k; j++) {
if ((x[j] == i) || Math.abs(x[j] - i) == Math.abs(j - k)) {
return 0;
}
}
return 1;
}
public static void main(String[] args) {
int n;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Value of N:");
n = scanner.nextInt();
if(n<4){
System.out.println("Invalid input, n should be greater or equal than 4");
}
else{
NQueen(1, n);
}
}
}