问题描述
- n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
解题思路
- 使用DFS和回溯法
- 按行进行搜索,得到一个正确解或者无法得到正确解,则往上回溯寻找求他解
实现思路和代码如下
class Solution {
public ArrayList<List<String>> solveNQueens(int n) {
ArrayList<List<String>> result = new ArrayList<>();
if (n <= 0) {
return result;
}
char[][] board = new char[n][n];
init(board);
dfsEachSolution(result, board, 0);
return result;
}
private void dfsEachSolution(ArrayList<List<String>> result, char[][] board, int rowIndex) {
if (rowIndex == board.length) {
result.add(boardArrayToList(board));
}
for (int colIndex = 0; colIndex < board.length; colIndex++) {
if (isValid(rowIndex, board, colIndex)) {
board[rowIndex][colIndex] = 'Q';
dfsEachSolution(result, board, rowIndex + 1);
board[rowIndex][colIndex] = '.';
}
}
}
private boolean isValid(int rowIndex, char[][] board, int colIndex) {
for (int x = 0; x < rowIndex; x++) {
if (board[x][colIndex] == 'Q') {
return false;
}
}
for (int x = rowIndex - 1, y = colIndex + 1; x >= 0 && y < board.length; x--, y++) {
if (board[x][y] == 'Q') {
return false;
}
}
for (int x = rowIndex - 1, y = colIndex - 1; x >= 0 && y >= 0; x--, y--) {
if (board[x][y] == 'Q') {
return false;
}
}
return true;
}
private void init(char[][] board) {
for (int lineIndex = 0; lineIndex < board.length; lineIndex++) {
Arrays.fill(board[lineIndex], '.');
}
}
private List<String> boardArrayToList(char[][] board) {
List<String> boardList = new ArrayList<>();
for (int rowIndex = 0; rowIndex < board.length; rowIndex++) {
StringBuilder sb = new StringBuilder();
for (int colIndex = 0; colIndex < board.length; colIndex++) {
sb.append(board[rowIndex][colIndex]);
}
boardList.add(sb.toString());
}
return boardList;
}
}