forked from Harshita-Kanal/Data-Structures-and-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNQueen.java
More file actions
81 lines (75 loc) · 1.92 KB
/
NQueen.java
File metadata and controls
81 lines (75 loc) · 1.92 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
import java.util.*;
class Solution8 {
String board[][];
boolean colums[];
boolean left[];
boolean right[];
Set<List<String>>lists;
public List<List<String>> solveNQueens(int n) {
board = new String[n][n];
for (String arr[] : board) {
Arrays.fill(arr, ".");
}
lists=new HashSet<>();
colums = new boolean[n];
left = new boolean[2 * n - 1];
right = new boolean[2 * n - 1];
solve(0,n);
return new ArrayList<>(lists);
}
void solve(int i,int n)
{
if (i==n)
{
List<String>list=new ArrayList<>();
for (int i1=0;i1<board.length;i1++)
{
String res="";
for (int j1=0;j1<board[0].length;j1++)
{
res=res+board[i1][j1];
}
list.add(res);
}
lists.add(list);
return;
}
for (int col=0;col<n;col++)
{
if (issafe(i,col,n)==true)
{
board[i][col]="Q";
colums[col]=true;
left[i+col]=true;
right[i-col+n-1]=true;
solve(i+1,n);
board[i][col]=".";
colums[col]=false;
left[i+col]=false;
right[i-col+n-1]=false;
}
}
}
boolean issafe(int i,int j,int n)
{
if (colums[j]==true)
{
return false;
}
if (left[i+j]==true)
{
return false;
}
if (right[i-j+n-1]==true)
{
return false;
}
return true;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
Solution8 solution8=new Solution8();
System.out.println(solution8.solveNQueens(n));
}
}