zoukankan      html  css  js  c++  java
  • 51_n皇后

    class Solution {
        List<List<String>> res;
        //检查 列+主对角+负对角
        boolean[] cols;
        boolean[] poss;
        boolean[] negs;
        char[][] t;
        int m ;
        public List<List<String>> solveNQueens(int n) {
            //初始化
            m = n;
            t = new char[n][n];
            for (char[] c : t) {
                Arrays.fill(c, '.');
            }
            res = new ArrayList<>();
            cols = new boolean[n];
            poss = new boolean[2*n-1];
            negs = new boolean[2*n-1];
            backtrace(0);
            return res;
        }
        //需要什么参数呢?
        private void backtrace(int r){
            //赢了 添加结果
                //语义应该是到了n+1了
            if(r == m){
                List<String> winner = transform();
                res.add(winner);
                return ;
            }
            //同层横向走
            for(int i = 0;i<m;i++){
                if(isValid(r,i)){
                    //当前可以行
                    t[r][i] = 'Q';
                    cols[i] = true;
                    poss[r+i] = true;
                    negs[r-i+m-1] = true;
                    backtrace(r+1);
                    t[r][i] = '.';
                    cols[i] = false;
                    poss[r+i] = false;
                    negs[r-i+m-1] = false;
                }
            }
        }
    
        private boolean isValid(int r,int c){
            if(cols[c] ) return false;
            if(poss[r+c]) return false;
            if(negs[r-c+m-1]) return false;
            return true;
        }
        private List<String> transform(){
            List<String> res = new ArrayList<>();
            for(char[] e:t){
                res.add(new String(e));
            }
            return res;
        }
    }
  • 相关阅读:
    Delphi程序结构
    SQL存储过程解密 Encrypted object is not transferable, and script can not be generated

    在河南呢
    还在河南,写随笔吧
    HAVING
    mIRC
    关于CAP理论
    开篇
    移动信息系统
  • 原文地址:https://www.cnblogs.com/purexww/p/15178654.html
Copyright © 2011-2022 走看看