Untitled
unknown
java
a year ago
1.7 kB
6
Indexable
class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
dfs(res, new ArrayList<>(), n, 0);
return res;
}
private void dfs(List<List<String>> res, List<String> temp, int n, int row) {
if (row == n) {
res.add(new ArrayList<>(temp));
return;
}
for (int j = 0; j < n; j++) {
if (isValid(row, j, n, temp)) {
temp.add(createRowString(j, n));
dfs(res, temp, n, row + 1);
temp.remove(temp.size() - 1);
}
}
}
private String createRowString(int idx, int n) {
String res = "";
for (int i = 0; i < n; i++) {
if (i == idx) {
res = res + "Q";
} else {
res = res + ".";
}
}
return res;
}
private boolean isValid(int row, int col, int n, List<String> temp) {
if (row == 0)
return true;
// check col
for (int i = 0; i < row; i++) {
if (temp.get(i).charAt(col) == 'Q') {
return false;
}
}
// check northwest
int i = row, j = col;
while (i - 1 >= 0 && j - 1 >= 0) {
if (temp.get(i - 1).charAt(j - 1) == 'Q') {
return false;
}
i--;
j--;
}
// check northeast
i = row;
j = col;
while (i - 1 >= 0 && j + 1 < n) {
if (temp.get(i - 1).charAt(j + 1) == 'Q') {
return false;
}
i--;
j++;
}
return true;
}
}Editor is loading...
Leave a Comment