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

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/13187903.html