class Solution {
List<List<String>> result;
int[] queens;
Set<Integer> columns = new HashSet<>();
Set<Integer> diaArr1 = new HashSet<>(); // 正对角线
Set<Integer> diaArr2 = new HashSet<>(); // 反对角线
public List<List<String>> solveNQueens(int n) {
result = new ArrayList<>();
queens = new int[n];
Arrays.fill(queens, -1);
dfs(n, 0);
return result;
}
private void dfs(int n, int row) {
if (row == n) {
List<String> board = generated(n);
result.add(board);
return;
}
for (int col = 0; col < n; col++) {
if (columns.contains(col)) {
continue;
}
int dia1 = row - col;
if (diaArr1.contains(dia1)) {
continue;
}
int dia2 = row + col;
if (diaArr2.contains(dia2)) {
continue;
}
queens[row] = col;
columns.add(col);
diaArr1.add(dia1);
diaArr2.add(dia2);
dfs(n, row + 1);
// queens[row] = -1;
columns.remove(col);
diaArr1.remove(dia1);
diaArr2.remove(dia2);
}
}
private List<String> generated(int n) {
List<String> board = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
char[] row = new char[n];
Arrays.fill(row, '.');
row[queens[i]] = 'Q';
board.add(new String(row));
}
return board;
}
}
07-15
786
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-14
482
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-14
918
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-14
231
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-25
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交