class Solution {
int[] dp;
List<List<String>> list ;
Set<Integer> x ;
Set<Integer> y;
Set<Integer> z;
public List<List<String>> solveNQueens(int n) {
dp = new int[n];
// 初始化
Arrays.fill(dp, -1);
list = new ArrayList<>();
x = new HashSet<>();
y = new HashSet<>();
z = new HashSet<>();
calculation(n, 0, dp, x, y ,z);
return list;
}
private void calculation(int n, int row, int[] dp, Set<Integer> x, Set<Integer> y, Set<Integer> z){
if (n == row){
List<String> board = buildBoard(dp, n);
list.add(board);
return;
} else {
for (int i = 0 ; i < n; i++){
if (x.contains(i)){
continue;
}
int y1 = row - i;
if (y.contains(y1)){
continue;
}
int z1 = row + i;
if (z.contains(z1)){
continue;
}
dp[row] = i;
x.add(i);
y.add(y1);
z.add(z1);
calculation(n, row + 1, dp, x, y, z);
dp[row] = -1;
x.remove(i);
y.remove(y1);
z.remove(z1);
}
}
}
private List<String> buildBoard(int[] dp, int n){
List<String> res = new ArrayList<>();
for (int i = 0; i < n; i++){
char[] board = new char[n];
Arrays.fill(board, '.');
board[dp[i]] = 'Q';
res.add(new String(board));
}
return res;
}
}
力扣:51. N 皇后
最新推荐文章于 2025-07-22 18:03:35 发布