LeetCode51. N皇后

LeetCode题目51. N皇后

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
LeetCode51. N皇后_第1张图片
上图为 8 皇后问题的一种解法。

给定一个整数 n,返回所有不同的 n 皇后问题的解决方案。

每一种解法包含一个明确的 n 皇后问题的棋子放置方案,该方案中 ‘Q’ 和 ‘.’ 分别代表了皇后和空位。

示例1
输入: 4
输出: [
[".Q…", // 解法 1
“…Q”,
“Q…”,
“…Q.”],

["…Q.", // 解法 2
“Q…”,
“…Q”,
“.Q…”]
]
解释: 4 皇后问题存在两个不同的解法。


解题思路

重在理解n皇后问题的规则:每一行,每一列,每一个对角线只能出现一个皇后。
我们按行添加’Q’, 又对角线分为45度对角线和135度对角线,所以我们用三个布尔数组分别记录在不同列,不同对角线上是否已经有‘Q’存在。
其中,45度对角线对应的布尔数组长度为2*n+1, 数组下标与棋盘的对应关系是:index=row+col;
LeetCode51. N皇后_第2张图片

135度对角线对应的布尔数组长度为2*n+1, 数组下标与棋盘的对应关系是:index= n - 1 - (row - col);

LeetCode51. N皇后_第3张图片

完整代码

public class solveNQueens_51_N皇后 {
    private List<List<String>> res = new ArrayList<>();
    private int n;
    private char[][] chs;
    boolean[] colExist;//列
    boolean[] _45degExist;//45度对角线
    boolean[] _135degExist;//135度对角线

    public List<List<String>> solveNQueens(int n) {
        this.n = n;
        chs = new char[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(chs[i], '.');
        }
        if (n <= 0)
            return res;
        this.colExist = new boolean[n];//列
        this._45degExist = new boolean[2 * n - 1];//45度对角线
        this._135degExist = new boolean[2 * n - 1];//135度对角线
        trace(0);//从第一行开始
        return res;
    }

    private void trace(int row) {
        if (row == n) {
            List<String> list = new ArrayList<>();
            for (char[] ch : chs) {
                list.add(new String(ch));
            }
            res.add(list);
            return;
        }
        for (int col = 0; col < n; col++) {
            if (colExist[col] || _45degExist[row + col] || _135degExist[n - 1 - (row - col)])
                continue;
            chs[row][col] = 'Q';
            colExist[col] = true;
            _45degExist[row + col] = true;
            _135degExist[n - 1 - (row - col)] = true;
            trace(row + 1);
            chs[row][col] = '.';
            colExist[col] = false;
            _45degExist[row + col] = false;
            _135degExist[n - 1 - (row - col)] = false;
        }
    }
}

更多LeetCode题目及答案解析见GitHub: https://github.com/on-the-roads/LeetCode
剑指offer题目及答案解析:https://github.com/on-the-roads/SwordToOffer

你可能感兴趣的:(LeetCode题解)