zoukankan      html  css  js  c++  java
  • 51. N皇后

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

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

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

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

    示例:

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

    class Solution {
        Set<Integer> rset;
        Set<Integer> posset;
        Set<Integer> negset;
        int n;
        public List<List<String>> solveNQueens(int n) {
            //准备三个HashSet,回溯
            List<List<String>> lists = new ArrayList<>();
            if(n <= 0) return lists;
            this.n = n;
            rset = new HashSet<>();
            posset = new HashSet<>();
            negset = new HashSet<>();
            bt(0,n,new ArrayList<String>(),lists);
            return lists;
        }
        
        private void bt(int i,int n,List<String> list,List<List<String>> lists){
            //达到第n - 1行,退出
            if(i == n){
                lists.add(new ArrayList<>(list));
                return;
            }
            //递归模拟行的递增,循环模拟每行上列的增加
            for(int j = 0;j < n;j++){
                if(!rset.contains(j) && !posset.contains(i - j) &&  !negset.contains(i + j)){
                    rset.add(j);
                    posset.add(i - j);
                    negset.add(i + j);
                    char[] s = new char[n];
                    Arrays.fill(s,'.');
                    s[j] = 'Q';
                    list.add(new String(s));
                    bt(i + 1,n,list,lists);
                    list.remove(list.size() - 1);
                    rset.remove(j);
                    posset.remove(i - j);
                    negset.remove(i + j);
                }
            }           
        }
    }
    一回生,二回熟
  • 相关阅读:
    leetcode 刷题日志 2018-03-26
    WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping
    sublime wrong
    SSM框架使用-wrong
    C++设计实现算法时易犯错误
    CodeBlocks wrong
    leetcode 刷题日志 2018-3-28
    CountDownLatch
    类加载器和双亲委派
    GC的一个面试题
  • 原文地址:https://www.cnblogs.com/zzytxl/p/12667573.html
Copyright © 2011-2022 走看看