解答
java
class Solution {
public List<List<String>> solveNQueens(int n) {
int[][] chestPanel = new int[n][n];
for (int i = 0; i < n; ++i) {
Arrays.fill(chestPanel[i], 0);
}
List<List<String>> results = new ArrayList<>();
solveNQueens(n, results, chestPanel, 0);
return results;
}
public void solveNQueens(int n, List<List<String>> results, int[][] chestPanel, int row) {
if (row == n) {
List<String> lines = new ArrayList<>();
for (int i = 0; i < n; ++i) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; ++j) {
if (chestPanel[i][j] == 1) {
sb.append("Q");
} else {
sb.append(".");
}
}
lines.add(sb.toString());
}
results.add(lines);
return;
}
for (int i = 0; i < n; ++i) {
if (isValidPosition(chestPanel, row, i)) {
chestPanel[row][i] = 1;
solveNQueens(n, results, chestPanel, row + 1);
chestPanel[row][i] = 0;
} else {
chestPanel[row][i] = 0;
}
}
}
public boolean isValidPosition(int[][] chestPanel, int currentRow, int currentColomn) {
int n = chestPanel.length;
if (currentColomn >= n || currentRow >= n) {
return false;
}
// 当前列
for (int i = 0; i < currentRow; ++i) {
if (chestPanel[i][currentColomn] == 1) {
return false;
}
}
// 左上角
for (int i = currentRow - 1, j = currentColomn - 1; i >= 0 && j >= 0; --i, --j) {
if (chestPanel[i][j] == 1) {
return false;
}
}
// 右上角
for (int i = currentRow - 1, j = currentColomn + 1; i >= 0 && j < n; --i, ++j) {
if (chestPanel[i][j] == 1) {
return false;
}
}
return true;
}
}
总结
回溯法。