八皇后问题

    技术2025-09-27  29

    设计一种算法,打印 N 皇后在 N × N 棋盘上的各种摆法,其中每个皇后都不同行、不同列,也不在对角线上。这里的“对角线”指的是所有的对角线,不只是平分整个棋盘的那两条对角线。

    注意:本题相对原题做了扩展

    示例:

    输入:4 输出:[[".Q…","…Q",“Q…”,"…Q."],["…Q.",“Q…”,"…Q",".Q…"]] 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q…", // 解法 1 “…Q”, “Q…”, “…Q.”],

    ["…Q.", // 解法 2 “Q…”, “…Q”, “.Q…”] ]

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/eight-queens-lcci

    下面直接给出解法,有时间再更新教程

    class Solution { private List<List<String>> result = new ArrayList(); //定义了一个临时变量来存储每个皇后选择的列号,其实这里还存储了 //皇后的行号,tmp的坐标就代表了皇后的行号,这点非常关键 private Integer[] tmp = null; // {0, 4, 7....} public List<List<String>> solveNQueens(int n) { tmp = new Integer[n]; // {0, 4, 7....} List<List<Integer>> result1 = new ArrayList(); dfs(n,0, result1); result1.forEach(list ->{ List<String> ppp = new ArrayList<>(); list.forEach(index -> { String s = ""; for (int i = 0; i < n ; i++) { if (i == index){ s = s + "Q"; }else { s = s + "."; } } ppp.add(s); }); result.add(ppp); }); return result; } public void dfs(int n, int index, List<List<Integer>> result){ if (index == n){ result.add(new ArrayList<>(Arrays.asList(tmp))); return; } for (int i = 0; i < n ; i++) { //赋值列的位置给皇后 tmp[index] = i; if (check(index)){ //回溯 dfs(n, index + 1, result); } } } /** * check下该皇后是否满足 * @param index 表示第几个皇后 * @return */ public boolean check(int index){ for (int i = 0; i < index; i++) { /** 判断该皇后是否于tmp里的在一条列上;Math.abs(index - i) == Math.abs(tmp[index] - tmp[i])可以理解为判断斜率是否为1,想想一下数学中的y=x,当斜率为1说明在一条对角线上 */ if (tmp[i] == tmp[index] || Math.abs(index - i) == Math.abs(tmp[index] - tmp[i])){ return false; } } return true; } }
    Processed: 0.017, SQL: 10