前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >穷举vs暴搜vs深搜vs回溯vs剪枝系列一>N 皇后

穷举vs暴搜vs深搜vs回溯vs剪枝系列一>N 皇后

作者头像
用户11305962
发布2025-01-19 13:10:19
发布2025-01-19 13:10:19
3900
代码可运行
举报
文章被收录于专栏:学习
运行总次数:0
代码可运行

题目: 


解析:

1.决策树: 


代码设计: 


根据决策树剪枝设计: 


代码:

代码语言:javascript
代码运行次数:0
复制
class Solution {
    private List<List<String>> ret;
    private char[][] path;
    private boolean[] checkdig1,checkdig2,checkcol;
    int n;

    public List<List<String>> solveNQueens(int _n) {
        n = _n;
        ret = new ArrayList<>();
        path = new char[n][n];
        checkcol = new boolean[n];//判断列有没有n皇后
        checkdig1 = new boolean[2*n];//判断主对角线有没有n皇后
        checkdig2 = new boolean[2*n];//判断副对角线有没有n皇后



        for(int i = 0; i < n; i++)
            Arrays.fill(path[i],'.');    

        dfs(0);
        return ret;
    }

    private void dfs(int row){
        if(row == n){
            List<String> tmp = new ArrayList<>();  
            for(int i = 0; i < n; i++){
                tmp.add(new String(path[i]));
            }
            ret.add(new ArrayList<>(tmp));
            return;
        } 

        for(int col = 0; col < n; col++){

            //剪枝写法,能不能放N 皇后:
            if(checkcol[col] == false && checkdig1[col-row+n] == false && checkdig2[col+row] == false){
                path[row][col] = 'Q';
                checkcol[col] = checkdig1[col-row+n] = checkdig2[col+row] = true;
                dfs(row+1);

                //恢复现场
                path[row][col] = '.';
                checkcol[col] = checkdig1[col-row+n] = checkdig2[col+row] = false;
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-01-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档