思路:
// @Title: N 皇后 (N-Queens)
// @Author: qisiii
// @Date: 2024-09-21 17:56:11
// @Runtime: 2 ms
// @Memory: 43.9 MB
// @comment:
// @flag:
class Solution {
public List<List<String>> solveNQueens(int n) {
char[][] matrix = new char[n][n];
for (char[] row : matrix) {
Arrays.fill(row, '.');
}
List<List<String>> result = new ArrayList<>();
dfs(result, matrix, n, 0);
return result;
}
private void dfs(List<List<String>> result, char[][] matrix, int n, int row) {
if (row == n) {
List<String> temp = new ArrayList<>();
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
sb.append(matrix[i][j]);
}
temp.add(sb.toString());
}
result.add(temp);
return;
}
for (int j = 0; j < n; j++) {
if (isValid(row, j,matrix)) {
matrix[row][j] = 'Q';
dfs(result, matrix, n, row + 1);
matrix[row][j] = '.';
}
}
}
private boolean isValid(int row, int column, char[][] matrix) {
for (int j = 0; j < row; j++) {
if (matrix[j][column] == 'Q') {
return false;
}
}
for (int i = row - 1, j = column - 1; i >= 0 && j >= 0; i--, j--) {
if (matrix[i][j] == 'Q') {
return false;
}
}
for (int i = row - 1, j = column + 1; i >= 0 && j < matrix.length; i--, j++) {
if (matrix[i][j] == 'Q') {
return false;
}
}
return true;
}
}