cherrychenlee

导航

 

原文地址:https://www.jianshu.com/p/34782400bc16

时间限制: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

posted on 2019-05-07 13:24  cherrychenlee  阅读(123)  评论(0编辑  收藏  举报