首页 > 试题广场 >

矩阵中的路径

[编程题]矩阵中的路径
  • 热度指数:9539 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
示例1

输入

"ABCESFCSADEE",3,4,"ABCCED"

输出

true
示例2

输入

"ABCESFCSADEE",3,4,"ABCB"

输出

false
class Solution:
    # main
    def hasPath(self , matrix : str , rows : int  , cols : int , string : str ):
        #1.special cases
        if len(string)>len(matrix):
            return False
        if len(matrix)!= rows*cols:
            return False
        if rows<0&nbs***bsp;cols<0:
            return False
        
        # 2.construct matrix by string
        matrixList = []
        for i in range(rows):
            matrixList.append(list(matrix[i*cols:i*cols+cols]))
        #print(matrixList)
        
        #3.search the location of the String's first char,which is in the matrixlist
        firstCharAppearIndex = []
        for row in range(rows):
            for col in range(cols):
                if matrixList[row][col]==string[0]:
                    firstCharAppearIndex.append((row,col))
        if len(firstCharAppearIndex)==0:
            return False
        
        #4.Traversal search the sequence,use recursion method
        for idxTuple in firstCharAppearIndex:
            if self.findResultPath(matrixList,idxTuple,string):
                return True
            
        # worst result,cannot find a path then return False
        return False


    def findResultPath(self, matrixList:list , idxTuple:tuple , string:str):
        # idxtuple(row,col) index location of the first character of string,that is string[0]
        # 1.special cases
        if (not 0<=idxTuple[0]<len(matrixList))&nbs***bsp;(not  0<=idxTuple[1]<len(matrixList[0]))&nbs***bsp;\
            (matrixList[idxTuple[0]][idxTuple[1]]!=string[0]):
                return False
        if len(string)==1 and matrixList[idxTuple[0]][idxTuple[1]]==string[0]:
                return True
        # 2.search the surrounding element whether is equal to string[1]
        else:
            matrixList[idxTuple[0]][idxTuple[1]]=""
            res = self.findResultPath(matrixList=matrixList,idxTuple=(idxTuple[0],idxTuple[1]-1),string=string[1:]) \
               &nbs***bsp;self.findResultPath(matrixList=matrixList,idxTuple=(idxTuple[0],idxTuple[1]+1),string=string[1:]) \
               &nbs***bsp;self.findResultPath(matrixList=matrixList,idxTuple=(idxTuple[0]+1,idxTuple[1]),string=string[1:]) \
               &nbs***bsp;self.findResultPath(matrixList=matrixList,idxTuple=(idxTuple[0]-1,idxTuple[1]),string=string[1:]) 
            matrixList[idxTuple[0]][idxTuple[1]]=string[0]
            return res

发表于 2022-01-30 00:00:04 回复(1)

问题信息

上传者:牛客301499号
难度:
1条回答 4909浏览

热门推荐

通过挑战的用户

矩阵中的路径