class Solution: def hasPath(self , matrix , word ): # write code here visited = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] for i in range(len(matrix)): for j in range(len(matrix[0])): if self.DFS(i,j,matrix,visited,word): return True return False def DFS(self, x, y, matrix, visited, word): if not word: return True if not visited[x][y]: if matrix[x][y] == word[0]: if len(word[1:]) == 0: return True visited[x][y] = 1 if y+1 <= len(matrix[0])-1 and self.DFS(x, y+1, matrix, visited, word[1:]): return True if x+1 <= len(matrix)-1 and self.DFS(x+1, y, matrix, visited, word[1:]): return True if x-1 >=0 and self.DFS(x-1, y, matrix, visited, word[1:]): return True if y-1 >= 0 and self.DFS(x, y-1, matrix, visited, word[1:]): return True visited[x][y] = 0 return False