zoukankan      html  css  js  c++  java
  • 回溯法

    是一种基于深度优先的试错算法,通常可以使用递归来解决。

    递归函数包括以下三个部分

    1、出口:定义在递归函数开始的地方。同时可以通过全局变量统计可行解的个数

    2、递归函数处理过程:取决于问题

    3、递归函数传参:用于探索解得可能性

    通过约束进行剪枝

    矩阵中的路径

    class Solution {
        public boolean exist(char[][] board, String word) {
            int row = board.length;
            int col =board[0].length;
            if(row==0||col==0)
                return false;
            boolean[][] visited = new boolean[row][col];
            for(int i =0;i<row;i++)
            {
                for(int j=0;j<col;j++)
                {
                    if(hasPathCore(board,i,row,j,col,visited,word,0))
                        return true;
                }
            }
            return false;
    }
    public boolean hasPathCore(char[][] board,int i,int row,int j ,int col,boolean[][]visited,String word,int pathCur)
    {
        if(word.length()==pathCur)
            return true;
        
        boolean hasPath =false;
        if(i>=0&&i<row&&j>=0&&j<col&&
            board[i][j]==word.charAt(pathCur)
            &&!visited[i][j])
            {
                pathCur++;
                visited[i][j]=true;
                hasPath=hasPathCore(board,i-1,row,j,col,visited,word,pathCur)||
                        hasPathCore(board,i+1,row,j,col,visited,word,pathCur)||
                        hasPathCore(board,i,row,j-1,col,visited,word,pathCur)||
                        hasPathCore(board,i,row,j+1,col,visited,word,pathCur);
                if(!hasPath)
                {
                    pathCur--;
                    visited[i][j]=false;
                }
            }
            return hasPath;
    }
    }
  • 相关阅读:
    flutter开发环境的搭建
    创建一个android项目
    android studio 安装与配置
    sentinel-dashboard.jar 安装
    三:nacos的配置中心
    二:nacos 的服务注册
    spring boot 在windows下的 批文件部署
    一:nacos 的安装与启动方式
    mysql 命令行安装方式
    Git 出现 Permission denied 时,重新生成ssh密钥
  • 原文地址:https://www.cnblogs.com/huchengxi/p/12536798.html
Copyright © 2011-2022 走看看