剑指offer——矩阵中的路径

题目描述:设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中任意一格开始,分别向上下左右四个方向都可以移动。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。

解题思路:这是一个回溯法的经典题,最常用就是递归来做。用递归解题的最主要问题就是要注意递归的边界条件。本题为目标字符串遍历完成,即可return。还有一点需要注意,就是题目中提及,矩阵中的每一格只能遍历一次,所以要有一个同样大小的矩阵来判断每一格是否被遍历过。

class Solution {
public:
    bool path(char *matrix,int rows,int cols,int row,int col,char *str,int& loc,bool *visited)
    {
        if(str[loc]=='\0')
        {
            return true;
        }
        bool haspath=false;
        if(row>=0 && row<rows &&col >=0 &&col<cols && 
           matrix[row*cols+col]==str[loc]&& visited[row*cols+col]==false)
        {
            loc++;
            visited[row*cols+col]=true;
            haspath=path(matrix,rows,cols,row-1,col,str,loc,visited)||
                path(matrix,rows,cols,row+1,col,str,loc,visited)||
                path(matrix,rows,cols,row,col-1,str,loc,visited)||
                path(matrix,rows,cols,row,col+1,str,loc,visited);
            if(!haspath)
            {
                loc--;
                visited[row*cols+col]=false;
            }
        }
        return haspath;
    }
    
    
    bool hasPath(char* matrix, int rows, int cols, char* str)
    {
        if(matrix==nullptr || rows==0 || cols==0 || str==nullptr)
        {
            return false;
        }
        bool res=false;
        int loc=0;
        bool *visited=new bool[rows*cols];
        memset(visited,0,rows*cols);
        for(int i=0;i<rows;i++)
        {
            for(int j=0;j<cols;j++)
            {
                res=path(matrix,rows,cols,i,j,str,loc,visited);
                if(res==true)
                {
                    return true;
                }
            }
        }
        delete []visited;
        return res;
    }


};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值