class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
int[] queens = new int[n];
Arrays.fill(queens, -1);
Set<Integer> colums1 = new HashSet<>();
Set<Integer> diagonals1 = new HashSet<>();
Set<Integer> diagonals2 = new HashSet<>();
calculation(res, queens, n, 0, colums1, diagonals1, diagonals2);
return res;
}
private void calculation(List<List<String>> res, int[] queens , int n , int row,
Set<Integer> colums1, Set<Integer> diagonals1, Set<Integer> diagonals2){
if (row == n){
List<String> board = generateBoard(queens, n);
res.add(new ArrayList<>(board));
return;
} else {
for (int i = 0; i < n; i++){
// 判断边是否已经可以添加
if (colums1.contains(i)){
continue;
}
int diagonal1 = row - i;
if (diagonals1.contains(diagonal1)){
continue;
}
int diagonal2 = row + i;
if (diagonals2.contains(diagonal2)){
continue;
}
queens[row] = i;
colums1.add(i);
diagonals1.add(diagonal1);
diagonals2.add(diagonal2);
// 判断下一个点
calculation(res, queens, n, row + 1, colums1, diagonals1, diagonals2);
// 结果重置
queens[row] = -1;
colums1.remove(i);
diagonals1.remove(diagonal1);
diagonals2.remove(diagonal2);
}
}
}
/**
* 拼接结果
* @param queens
* @param n
* @return
*/
private List<String> generateBoard(int[] queens, int n ){
List<String> board = new ArrayList<>();
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;
}
}
力扣:面试题 08.12. 八皇后
最新推荐文章于 2024-09-06 09:22:51 发布