• 52. N-Queens II


    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 the number of distinct solutions to the n-queens puzzle.

    Example:

    Input: 4
    Output: 2
    Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]
     class Solution {
         //public int res = 0;
        public int totalNQueens(int n) {
           // List<List<String>> result = new ArrayList<>();
            int[] C = new int[n]; // C[i]表示第i行皇后所在的列编号
            int[] res = {0};
            //int res = 0;
            dfs(C, 0,res);
            return res[0];
        }
        public  void dfs(int[] C, int row,int[] res) {
            final int N = C.length;
            if (row == N) { // 终止条件,也是收敛条件,意味着找到了一个可行解
                res[0]++;
                return;
            }
    
            for (int j = 0; j < N; ++j) {  // 扩展状态,一列一列的试
                final boolean ok = isValid(C, row, j);
                if (!ok) continue;  // 剪枝,如果非法,继续尝试下一列
                // 执行扩展动作
                C[row] = j;
                dfs(C, row + 1,res);
                // 撤销动作
                // C[row] = -1;
            }
        }
    
        /**
         * 能否在 (row, col) 位置放一个皇后.
         *
         * @param C 棋局
         * @param row 当前正在处理的行,前面的行都已经放了皇后了
         * @param col 当前列
         * @return 能否放一个皇后
         */
         public boolean isValid(int[] C, int row, int col) {
            for (int i = 0; i < row; ++i) {
                // 在同一列
                if (C[i] == col) return false;
                // 在同一对角线上
                if (Math.abs(i - row) == Math.abs(C[i] - col)) return false;
            }
            return true;
        }
    }

    把不要的都去掉就可以。

    记住int传到method里面是无法修改的,替代的方法有1.设置全局变量,2.用一个长为1的数组代替。

  • 相关阅读:
    kill -3 导出 thread dump
    JVM中锁优化,偏向锁、自旋锁、锁消除、锁膨胀
    Hibernate validator验证
    java子类实例初始化过程
    spring- properties 读取的五种方式
    Spring连接数据库的几种常用的方式
    缓存使用中的注意事项
    java动态代理原理
    classpath目录
    springmvc常用注解标签详解
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11555191.html
Copyright © 2020-2023  润新知