class Solution {
public List<List<String>> solveNQueens(int n) {
List<List<String>> res = new ArrayList<>();
char[][] board = new char[n][n];
for (char[] c : board) {
Arrays.fill(c, '.');
}
dfs(res, n, 0, board);
return res;
}
private void dfs(List<List<String>> res, int n, int row, char[][] board) {
if (row == n) {
res.add(Array2List(board));
return;
}
for (int col = 0; col < n; col++) {
if (isValid(row, col, n, board)) {
board[row][col] = 'Q';
dfs(res, n, row + 1, board);
board[row][col] = '.';
}
}
}
private List Array2List(char[][] board) {
List<String> list = new ArrayList<>();
for (char[] c : board) {
list.add(String.valueOf(c));
}
return list;
}
private boolean isValid(int row, int col, int n, char[][] board) {
for (int i = 0; i < row; ++i) {
if (board[i][col] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] == 'Q') {
return false;
}
}
for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
if (board[i][j] == 'Q') {
return false;
}
}
return true;
}
}
代码随想录训练营第三十期|第三十天|回溯算法part06|● 332.重新安排行程 ● 51. N皇后 ● 37. 解数独 ● 总结
最新推荐文章于 2024-09-10 23:34:31 发布