class Solution {
int result = 0;
int[] queens;
Set<Integer> columns = new HashSet<>();
Set<Integer> diaArr1 = new HashSet<>(); // 正对角线
Set<Integer> diaArr2 = new HashSet<>(); // 反对角线
public int totalNQueens(int n) {
queens = new int[n];
Arrays.fill(queens, -1);
dfs(n, 0);
return result;
}
private void dfs(int n, int row) {
if (row == n) {
result += 1;
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);
}
}
}
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)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交