DFS 矩阵深度搜索

给定一个二维字符矩阵,从一个节点开始,规定每次可以向四方向移动,但不能重复访问一个节点,

形成一条访问路径,现给定一个字符串,判断该矩阵是否存在该路径

a b c e
s f c s
a d e e

该矩阵可以形成的路径有 bcced     但不能形成  abcb的路径

思路:采用经典深度搜索策略,设置一个访问数组,控制4方向探索,直到匹配完路径

class Solution {
public:
    vector<bool> visit;
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
         for(int i=0;i<rows*cols;i++)
             visit.push_back(false);
    
        for(int i=0;i<rows;i++)
            for(int j=0;j<cols;j++)
            {
                int count=0;
                if(dfs(matrix,rows,cols,i,j,str,count))
                    return true;
            }
        return false;
    
    }
    //深搜递归函数  参数依次是 矩阵信息,当前访问的节点位置,匹配的字符串和当前的匹配位置
    bool dfs(char* matrix,int rows,int cols,int row,int col,char* str,int count)
    {
        
        //搜索边界
      
        if(count==strlen(str)) //匹配完所有字符
            return true;
        if(row<0 || row>=rows || col<0 || col>=cols)
            return false;
        if(visit[row*cols+col]==true)
            return false;
        char the_char=matrix[row*cols+col];//当前访问到的字符
        if(the_char!=str[count]) //不匹配
            return false;
        //匹配后,进入递归四方向搜索
        bool res=false;
        visit[row*cols+col]=true;//当前节点设置为已经访问
        if(dfs(matrix,rows,cols,row-1,col,str,count+1))
            return true;
        if(dfs(matrix,rows,cols,row+1,col,str,count+1))
            return true;
        if(dfs(matrix,rows,cols,row,col-1,str,count+1))
            return true;
        if(dfs(matrix,rows,cols,row,col+1,str,count+1))
            return true;
        visit[row*cols+col]=false;//关键点,搜索失败返回上一层时 需要改回节点没有被访问
        return false;
        
        
    }


};

猜你喜欢

转载自blog.csdn.net/qq_33369979/article/details/88377256
今日推荐