forked from darpanjbora/Java-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.java
More file actions
114 lines (75 loc) · 2.07 KB
/
NQueen.java
File metadata and controls
114 lines (75 loc) · 2.07 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
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Input:
* 2
* 1
* 4
* Output:
* [1 ]
* [2 4 1 3 ] [3 1 4 2 ]
*/
public class NQueen {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// test cases
int t = Integer.parseInt(br.readLine());
while (t-- > 0){
// matrix dimension
int N = Integer.parseInt(br.readLine());
solveNQ(N);
System.out.println();
}
}
private static void printResult(ArrayList<int[]> result, int N) {
StringBuilder sb = new StringBuilder();
for ( int[] arr : result){
sb.append("[");
for( int i=1; i<N; i++){
sb.append(arr[i]+" ");
}
sb.append("] ");
}
System.out.print(sb);
}
private static void solveNQ(int N) {
ArrayList<int[]> result = new ArrayList<>();
int[] a = new int[N+1];
solveNQUtil(result, N+1, a, 1);
if (result.size()>0)
{
printResult(result, N+1);
}
else
{
System.out.print(-1);
}
}
private static void solveNQUtil(ArrayList<int[]> result, int N,int[] a, int row) {
if ( row == N ){
int arr[] = new int[N];
for (int i = 1; i< N; i++){
arr[i] = a[i];
}
result.add(arr);
return;
}
for(int i = 1; i< N; i++){
a[row] = i;
if (isSafe(a, N, row, i)){
solveNQUtil(result, N, a , row+1);
}
}
}
private static boolean isSafe(int[] a, int n, int row, int col) {
if( row == 1)
return true;
for ( int i = row-1; i>0 ; i--){
if ( a[i] == col || a[i]+i == row+col || i - a[i] == row - col)
return false;
}
return true;
}
}