矩阵中的路径

作者: cherryleechen | 来源:发表于2019-05-07 13:23 被阅读0次

    时间限制:1秒 空间限制:32768K

    题目描述

    请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。例如 a b c e s f c s a d e e 这样的3 X 4矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

    我的代码

    class Solution {
    public:
        bool hasPath(char* matrix, int rows, int cols, char* str)
        {
            if(rows<1 || cols<1 || *str=='\0')
                return false;
            for(int i=0;i<rows;i++)
                for(int j=0;j<cols;j++)
                    if(hasPathCore(matrix,rows,cols,str,i,j))
                        return true;
            return false;
        }
        bool hasPathCore(char* matrix, int rows, int cols, char* str, 
                         int i, int j){
            if(*str=='\0' || str==nullptr)
                return true;
            bool res=false;
            if((i>=0)&&(i<rows)&&(j>=0)&&(j<cols)&&(matrix[i*cols+j]==*str)){
                matrix[i*cols+j]='\0';
                res=hasPathCore(matrix,rows,cols,str+1,i+1,j)||
                    hasPathCore(matrix,rows,cols,str+1,i-1,j)||
                    hasPathCore(matrix,rows,cols,str+1,i,j+1)||
                    hasPathCore(matrix,rows,cols,str+1,i,j-1);
                matrix[i*cols+j]=*str;
            }
            return res;
        }
    };
    

    运行时间:4ms
    占用内存:492k

    相关文章

      网友评论

        本文标题:矩阵中的路径

        本文链接:https://www.haomeiwen.com/subject/kpfloqtx.html