"ABCESFCSADEE",3,4,"ABCCED"
true
"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