leetcode 51 N queens问题解法

问题描述
  • 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] = '.';
            }
        }

    }

    /**
     * 检查该位置上的Q是否符合要求,因为每次都是生成一行,因此行天然是符合条件的
     */
    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], '.');
        }
    }

    /**
     * 将一种正确解从二维矩阵转换为list
     */
    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;
    }
}
发布了45 篇原创文章 · 获赞 8 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/iNiegang/article/details/103949879