题目传送地址: https://leetcode.cn/problems/n-queens/
代码如下:
//递归解法
public static List<List<String>> solveNQueens(int n) {
List<List<String>> lists = fillChessboard(n, n);
return lists;
}
//填充前row行
public static List<List<String>> fillChessboard(int n, int row) {
List<List<String>> result = new ArrayList<>();
if (row == 1) {
int i = 0;
while (i < n) {
StringBuilder stringBuilder = new StringBuilder();
int j=0;
while (j<n){
stringBuilder.append(".");
j++;
}
stringBuilder.replace(i, i + 1, "Q");
result.add(Arrays.asList(stringBuilder.toString()));
i++;
}
return result;
}
List<List<String>> list = fillChessboard(n, row - 1);
for (List<String> list1 : list) {
for (int col = 0; col < n; col++) {
//校验该坐标处是否合适
boolean validChessboard = validChessBoard(row, col, list1, n);
if (validChessboard) {
StringBuilder stringBuilder = new StringBuilder();
int j=0;
while (j<n){
stringBuilder.append(".");
j++;
}
stringBuilder.replace(col, col + 1, "Q");
List<String> list2 = new ArrayList<>(list1);
list2.add(stringBuilder.toString());
result.add(list2);
}
}
}
return result;
}
//校验该坐标处是否合适
public static boolean validChessBoard(int row, int col, List<String> chessboard, int n) {
//校验行
//校验列
int j = 0;
while (j < chessboard.size()) {
String str = chessboard.get(j);
char c = str.charAt(col);
if (c == 'Q') {
return false;
}
j++;
}
//校验正斜线
int rowIndex = chessboard.size() - 1;
int colIndex = col - 1;
while (rowIndex >= 0 && colIndex >= 0) {
String str = chessboard.get(rowIndex);
char c = str.charAt(colIndex);
if (c == '.') {
rowIndex--;
colIndex--;
} else {
return false;
}
}
//校验反斜线
rowIndex = chessboard.size() - 1;
colIndex = col + 1;
while (rowIndex >= 0 && colIndex < n) {
String str = chessboard.get(rowIndex);
char c = str.charAt(colIndex);
if (c == '.') {
rowIndex--;
colIndex++;
} else {
return false;
}
}
return true;
}