-
Notifications
You must be signed in to change notification settings - Fork 1
/
_0051_N_Queens.java
149 lines (122 loc) · 3.17 KB
/
_0051_N_Queens.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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// https://leetcode.com/problems/n-queens/
import java.util.*;;
public class _0051_N_Queens {
public static void main(String[] args) {
int n = 4;
Solution0051 obj = new Solution0051();
List<List<String>> ans = obj.solveNQueens(n);
}
}
class Solution0051 {
public List<List<String>> solveNQueens(int n) {
List<List<String>> ans = new ArrayList<>();
char[][] arr = new char[n][n];
for(char[] ch : arr)
{
Arrays.fill(ch, '.');
}
getQueens(ans, arr, n, 0);
return ans;
}
public void print(char[][] arr)
{
for(char[] ch : arr)
{
System.out.println(Arrays.toString(ch));
}
System.out.println("____________________________");
}
public void getQueens(List<List<String>> ans, char[][] arr, int n, int row)
{
if(row == n)
{
print(arr);
List<String> l = new ArrayList<>();
for(char[] c : arr)
{
l.add(Arrays.toString(c).replaceAll("[ ,]", "").replace("[", "").replace("]", ""));
}
ans.add(l);
return;
}
for(int col = 0 ; col < n; col++)
{
if(isSafe(arr, row, col))
{
arr[row][col] = 'Q';
getQueens(ans, arr, n, row+1);
arr[row][col] = '.';
}
}
return;
}
public boolean isSafe(char[][] arr, int row, int col)
{
// check row
for(int i = 0; i < arr.length; i++)
{
if(arr[row][i] == 'Q')
{
return false;
}
}
// check columns
for(int j = 0; j < arr.length; j++)
{
if(arr[j][col] == 'Q')
{
return false;
}
}
// Upper Left Diagonals
int rLeft = row;
int cLeft = col;
while(rLeft >= 0 && cLeft >= 0)
{
if(arr[rLeft][cLeft] == 'Q')
{
return false;
}
rLeft--;
cLeft--;
}
// check Uppper Right diagonals
int rRight = row;
int cRight = col;
while(rRight >= 0 && cRight < arr.length)
{
if(arr[rRight][cRight] == 'Q')
{
return false;
}
rRight--;
cRight++;
}
// check Lower Left diagonals
rLeft = row;
cLeft = col;
while(rLeft > arr.length && cLeft >= 0)
{
if(arr[rLeft][cLeft] == 'Q')
{
return false;
}
rLeft++;
cLeft--;
}
// check Lower Right diagonals
rRight = row;
cRight = col;
while(rRight > arr.length && cRight < arr.length)
{
if(arr[rRight][cRight] == 'Q')
{
return false;
}
rRight++;
cRight++;
}
// Queen is safe
return true;
}
}