【LeetCode】 51. N-Queens N皇后(Hard)(JAVA)

【LeetCode】 51. N-Queens N皇后(Hard)(JAVA)

题目地址: https://leetcode.com/problems/n-queens/

题目描述:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

题目大意

n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。

解题方法

1、n 皇后问题:上下,斜对角都不能有相同的存在
2、用三个数组分别记录,column、row + column、row - column
3、递归求出结果

class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        List<String> cur = new ArrayList<>();
        int[] col = new int[n];
        int[] rowPcol = new int[2 * n];
        int[] rowMcol = new int[2 * n];
        sH(res, cur, col, rowPcol, rowMcol, n);
        return res;
    }

    public void sH(List<List<String>> res, List<String> cur, int[] col, int[] rowPcol, int[] rowMcol, int n) {
        int row = cur.size();
        if (row >= n) {
            res.add(new ArrayList<>(cur));
            return;
        }
        for (int i = 0; i < n; i++) {
            if (col[i] > 0 || rowPcol[i + row] > 0 || rowMcol[row - i + n] > 0) continue;
            col[i] = 1;
            rowPcol[i + row] = 1;
            rowMcol[row - i + n] = 1;
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < n; j++) {
                if (i == j) {
                    sb.append('Q');
                } else {
                    sb.append('.');
                }
            }
            cur.add(sb.toString());
            sH(res, cur, col, rowPcol, rowMcol, n);
            col[i] = 0;
            rowPcol[i + row] = 0;
            rowMcol[row - i + n] = 0;
            cur.remove(cur.size() - 1);
        }
    }
}

执行用时 : 3 ms, 在所有 Java 提交中击败了 90.76% 的用户
内存消耗 : 42.1 MB, 在所有 Java 提交中击败了 5.09% 的用户

发布了81 篇原创文章 · 获赞 6 · 访问量 2293

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104773886
今日推荐