forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN-Queens.java
More file actions
50 lines (47 loc) · 1.28 KB
/
N-Queens.java
File metadata and controls
50 lines (47 loc) · 1.28 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
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> ans = new ArrayList <>();
helper(n, 0, new ArrayList<>(), ans);
return ans;
}
private void helper(int n, int row, List<Integer> selections, List<List<String>> ans) {
if (row == n) {
ans.add(convertToString(selections, n));
}
else {
for (int i = 0; i < n; i++) {
selections.add(i);
if (isValid(selections)) {
helper(n, row + 1, selections, ans);
}
selections.remove(selections.size() - 1);
}
}
}
private List <String> convertToString(List <Integer> selections, int n) {
List<String> ret = new ArrayList<>();
for (int i = 0; i < selections.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
if (j == selections.get(i)) {
sb.append("Q");
}
else {
sb.append(".");
}
}
ret.add(sb.toString());
}
return ret;
}
private boolean isValid(List <Integer> selections) {
int row = selections.size() - 1;
for (int i = 0; i < row; i++) {
int diff = Math.abs(selections.get(i) - selections.get(row));
if (diff == 0 || diff == row - i) {
return false;
}
}
return true;
}
}