矩阵中的路径(DFS)

 该题也是BFS(递归+回溯)的经典题目,这道题真是花了我不少时间去debug ,对dfs还是不过熟练,还要继续努力!!!

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix char字符型vector<vector<>> 
     * @param word string字符串 
     * @return bool布尔型
     */
   int flag=0,row,col;
   vector<vector<int> >visited;
    bool hasPath(vector<vector<char> >& matrix, string word) {
        // write code here
         row=matrix.size();//得到行和列
         col=matrix[0].size(); 
        visited = vector<vector<int> >(row, vector<int>(col, 0));//初始化为0
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col;j++)
            {
                if(matrix[i][j]==word[0])//找到第一个字符后
                {
                    dfs(i,j,0,matrix,word);//开始搜索 注意这里还传了一个0初始化cur,cur作为word的下标
                    if(flag)
                        return true;
                }
            }
        }
        return false;
    }
    void dfs(int x,int y,int cur,vector<vector<char> >& matrix, string word)
    {
        if(flag)//边界
        return ;
        if(x>=0&&x<row&&y>=0&&y<col&&visited[x][y]==0&&matrix[x][y]==word[cur])
        {
            if(cur==word.length()-1)//边界
            {
                flag=1;
                return ;
            }
            visited[x][y]=1;//记录走过
                dfs(x+1,y,cur+1,matrix,word);//分别是向上
                dfs(x,y+1,cur+1,matrix,word);//向右
                dfs(x-1,y,cur+1,matrix,word);//向下
                dfs(x,y-1,cur+1,matrix,word);//向左 走
            visited[x][y]=0;//回来的时候记得恢复
        }

    }
};



对DFS不熟悉的一定要自己去调试走一下啊喂~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZZZWWWFFF_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值