zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 52 N皇后 II

    52. N皇后 II

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

    上图为 8 皇后问题的一种解法。

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

    示例:

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

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

    class Solution {
       
        /**
         * 记录某列是否已有皇后摆放
         */
        private boolean col[];
    
        /**
         * 记录某条正对角线(左上右下)是否已有皇后摆放(某条对角线对应的摆放位置为 x - y + n - 1)
         */
        private boolean dia1[];
    
        /**
         * 记录某条斜对角线(左下右上)是否已有皇后摆放(某条对角线对应的摆放位置为 x + y)
         */
        private boolean dia2[];
    
        public int totalNQueens(int n) {
            // 依然可以使用 51 号问题的解决思路,但问题是有没有更好的方法
            col = new boolean[n];
            dia1 = new boolean[2 * n - 1];
            dia2 = new boolean[2 * n - 1];
            return putQueen(n, 0);
        }
    
        /**
         * 递归回溯方式摆放皇后
         *
         * @param n     待摆放皇后个数
         * @param index 已摆放皇后个数
         */
        private int putQueen(int n, int index) {
            int res = 0;
            if (index == n) {
                return 1;
            }
            // 表示在 index 行的第 i 列尝试摆放皇后
            for (int i = 0; i < n; i++) {
                if (!col[i] && !dia1[i - index + n - 1] && !dia2[i + index]) {
                    // 递归
                    col[i] = true;
                    dia1[i - index + n - 1] = true;
                    dia2[i + index] = true;
                    res += putQueen(n, index + 1);
                    // 回溯
                    col[i] = false;
                    dia1[i - index + n - 1] = false;
                    dia2[i + index] = false;
                }
            }
            return res;
        }
    
    }
    
  • 相关阅读:
    Linux中/etc目录下passwd和shadow文件
    Linux基本命令
    Linux目录结构说明与基本操作
    如何用虚拟机VMware Workstation安装CentOs-7
    VPP源码分析及流程图
    VPP环境搭建及配置
    【转】智能指针的交叉引用问题及解决方法
    二叉树的前 中 后 层序遍历
    排序算法
    C和C++的一些区别
  • 原文地址:https://www.cnblogs.com/a1439775520/p/12946870.html
Copyright © 2011-2022 走看看