玩转lee52 n皇后问题

14 篇文章 0 订阅
9 篇文章 0 订阅

思路 回溯法

找每一行index中 棋子应该放在的列号(i)
所以应该设几个标号

  1. 因为是一行一行摆放,因此这些 “皇后” 一定不在同一行,无需额外设置状态;

  2. 为了保证不再同一列, 设 col [ ] 数组设置标志位,如果占了就true

  3. 为了保证至少两个皇后不同时出现在主对角线或者副对角线,我们的策略是,只要 “检测” 到新摆放的 “皇后” 与已经摆放好的 “皇后” 冲突,就尝试摆放下一个位置,在 “无处安放” 的时候 “剪枝” 。

    下面我们研究一下主对角线或者副对角线上的元素有什么特性。我们此时能掌握的信息只有行和列的索引,不妨将它标注在棋盘上。
    在这里插入图片描述

  4. 如何输出正确的格式, 记住 row里存的是每一行的棋子的纵坐标,所以我们可以新建一个函数,然后两个for for循环,如果j等于row函数对应的i 则是棋子,否则不是,然后将字符串拼接,我们使用 stringbuilder ,这样一个答案就成了。

class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res=new ArrayList<>();
        if(n<=0) return res;
        boolean[] col=new boolean[n];
        boolean[] dia1=new boolean[2*n-1];
        boolean[] dia2=new boolean[2*n-1];
 
        helper(n, 0, new ArrayList<>(),res, col, dia1, dia2);
        return res;
    }
    
    //尝试在一个n皇后问题中,摆放第index行的皇后位置
    public void helper(int n, int index, List<Integer> row, List<List<String>> res, boolean[] col, boolean[] dia1,boolean[] dia2){
        if(index==n){
            res.add( generateBoard(n,row));
            return ;
        }
        for(int i=0;i<n;i++){
            //尝试将第index行的皇后摆放在第i列
            if( !col[i] && !dia1[index+i] && !dia2[index-i+n-1]){
                row.add(i);
                col[i]=true;
                dia1[index+i]=true;
                dia2[index-i+n-1]=true;
                helper(n, index+1,row, res,col, dia1, dia2);
                col[i]=false;
                dia1[index+i]=false;
                dia2[index-i+n-1]=false;
                row.remove(row.size()-1);
            }
        }
        return;
    }

    public List<String> generateBoard(int n, List<Integer> row){
        List<String> list=new ArrayList<>();
        for(int i=0;i<n;i++){
            StringBuilder str=new StringBuilder();
            for(int j=0;j<n;j++){
                if(j==row.get(i))
                    str.append("Q");
                else
                    str.append(".");
             }
            list.add(str.toString());
         }
         return list;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值