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

    class Solution {
        //定义一个数组,用于存放每一列的皇后放置的位置
    
        List<List<String>> result = new ArrayList<>();
        public List<List<String>> solveNQueens(int n) {    //N皇后
            int[] cols = new int[n];
            return this.getCount(0,n,cols);
        }
    
        private List<List<String>> getCount(int s,int n,int[] cols) {
            //定义一个boolean数组,用于表明可以放置的位置
            boolean[] rows = new boolean[n];
            for(int m = 0;m<s;m++){  //与之前放置好的位置相联系,寻找第n列不可以放置的位置,进行标记
                rows[cols[m]] = true;
                int d = s - m;
                if(cols[m] - d >= 0){
                    rows[cols[m] - d] = true;
                }
                if(cols[m] + d < n){
                    rows[cols[m] + d] = true;
                }
            }
            for(int i = 0;i<n;i++){
                if(rows[i]){
                    continue;
                }
                cols[s] = i;
                if(s<n-1){
                    getCount(s+1,n,cols);
                }else{
                    result.add(queen(n,cols));
                }
            }
            return result;
    
        }
    
        private List<String> queen(int n,int[] cols) {
            List<String> list = new ArrayList<>();
            for(int i = 0;i<n;i++){
                StringBuilder s = new StringBuilder();
                for(int j = 0;j<n;j++){
                    if(i == cols[j]){
                        s.append("Q");
                    }else{
                        s.append(".");
                    }
                }
                list.add(s.toString());
            }
            return list;
        }
    }

    对于回溯还是没熟练掌握,这道题的回溯体现在在for循环里,

    if(s<n-1){
                    getCount(s+1,n,cols);

    加油冲!

    ——2020.6.24

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    hdu 4638 Group 线段树
    hdu 4635 Strongly connected 强连通分量
    hdu 4604 Deque
    hdu 1000 A + B Problem
    数组相关
    文本文件相关
    硬件电路中VCC,VDD,VEE,VSS有什么区别
    VIPM链接LabVIEW问题
    Touch实现轻扫
    touchesMoved 实现拖拽
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13187903.html
Copyright © 2011-2022 走看看