当前位置: 首页 > article >正文

【hot100-java】N 皇后

回溯篇

视频题解 

真的裂开了,多看视频题解。

class Solution {
    public List<List<String>> solveNQueens(int n) {
           List<List<String>>ret=new ArrayList<>();
           int []col=new int[n];
           boolean[] onPath=new boolean[n];
           boolean[] diag1=new boolean[n*2-1];
           boolean[] diag2=new boolean[n*2-1];
           dfs(0,n,col,onPath,diag1,diag2,ret);
           return ret;
    }
    private void dfs(int r,int n,int[] col,boolean[] onPath,boolean[] diag1,boolean[] diag2,List<List<String>>ret){
        if(r==n){
            List<String>board=new ArrayList<>(n);
            for(int c:col){
                char[] row = new char[n];
                Arrays.fill(row,'.');
                row[c]='Q';
                board.add(new String(row));
            }
            ret.add(board);
            return;
        }
        
        for (int c=0;c<n;c++){
            int rc=r-c+n-1;
            if(!onPath[c]&&!diag1[r+c]&&!diag2[rc]){
                col[r]=c;
                onPath[c]=diag1[r+c]=diag2[rc]=true;
                dfs(r+1,n,col,onPath,diag1,diag2,ret);
                //恢复现场
                onPath[c]=diag1[r+c]=diag2[rc]=false;
            }
        }
    }
}


http://www.kler.cn/news/340968.html

相关文章:

  • JavaScript 网页设计案例与技巧
  • Linux入门3——vim的简单使用
  • GEE 教程:利用Landsat函数计算不同缓冲区内的NDVI,NDWI和EVI的平均值
  • Django makemigrations时出现TypeError: ‘module‘ object is not iterable
  • minio简单使用
  • PostgreSQL中WITH查询公用表表达式
  • Jenkins新安装的插件ThinBackup,如何恢复之前的备份
  • YOLOv5改进——普通卷积和C3模块更换为GhostConvV2卷积和C3GhostV2模块
  • GO网络编程(五):海量用户通信系统3:整体框架与C/S通信总体流程【重要】
  • 解决github每次pull push输入密码问题
  • opencascade鼠标拖拽框选功能
  • Java | Leetcode Java题解之第468题验证IP地址
  • Windows10的MinGW安装和VS Code配置C/C++编译环境
  • mermaid 图表相关
  • 408算法题leetcode--第29天
  • 如何让你的Mac右键菜单栏更加的丰富多样
  • Vue vben admin开源库中table组件tips
  • 数据结构进阶:二叉搜索树_C++
  • YOLO11 实例分割模型做行人分割
  • 【10086网上营业厅-注册/登录安全分析报告】