forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathN-Queen-Problem
66 lines (62 loc) · 1.72 KB
/
N-Queen-Problem
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
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
static void printSolution(int pos[][])
{
System.out.print("[");
for(int i=0 ; i<pos.length ; i++)
for(int j=0 ; j<pos.length ; j++)
if(pos[j][i] == 1)
System.out.print((j+1) + " ");
System.out.print("] ");
}
static boolean isSafe(int pos[][],int row, int col)
{
for(int i=0 ; i<col ; i++)
if(pos[row][i] == 1)
return false;
for(int r=row, c=col ; r>=0 && c>=0; r--, c--)
if(pos[r][c] == 1)
return false;
for(int r=row, c=col ; r<pos.length && c>=0 ; r++, c--)
if(pos[r][c] == 1)
return false;
return true;
}
static boolean solve(int pos[][], int col)
{
if(col == pos.length)
{
printSolution(pos);
return true;
}
boolean res = false;
for(int i=0 ; i<pos.length ; i++)
{
if(isSafe(pos, i, col))
{
pos[i][col] = 1;
if(solve(pos, col+1) == true)
return true;
pos[i][col] = 0;
}
}
return res;
}
public static void main (String[] args) throws Exception
{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
while(t-- > 0)
{
int n = Integer.parseInt(bf.readLine());
int pos[][] = new int[n][n];
if(!solve(pos, 0))
System.out.println("-1");
else
System.out.println();
}
}
}