思想思路比较简单,遍历所有的元素,找到word首元素之后,开始向四周遍历,如果存在多个方向的元素都对,将这几个方向的位置都记录下来,并取其中一个方向开始遍历,同时将遍历过的位置记录下来。之后如果该方向不对,则将遍历过的位置恢复为未遍历过,并继续选取另一个方向开始遍历。直到遍历到所有的路径,或者遍历完所有的元素都没有路径
class Solution: def hasPath(self , matrix: List[List[str]], word: str) -> bool: # write code here iMax = len(matrix) jMax = len(matrix[0]) for i in range(iMax): for j in range(jMax): if matrix[i][j] == word[0]: if self.findPath(matrix, word, i, j, iMax, jMax): return True return False def findPath(self, matrix: List[List[str]], word: str, i:int, j:int, iMax:int, jMax:int): wId = 1 ls = [(i, j)] rpLs = [] while wId < len(word): repeatLs = [] if i + 1 < iMax and not ls.__contains__((i + 1, j)) and matrix[i + 1][j] == word[wId]: repeatLs.append((i + 1, j, wId + 1)) if i - 1 >= 0 and not ls.__contains__((i - 1, j)) and matrix[i - 1][j] == word[wId]: repeatLs.append((i - 1, j, wId + 1)) if j + 1 < jMax and not ls.__contains__((i, j + 1)) and matrix[i][j + 1] == word[wId]: repeatLs.append((i, j + 1, wId + 1)) if j - 1 >= 0 and not ls.__contains__((i, j - 1)) and matrix[i][j - 1] == word[wId]: repeatLs.append((i, j - 1, wId + 1)) if len(repeatLs) == 1: (i, j, wId) = repeatLs[0] ls.append((i, j)) elif len(repeatLs) > 1: (i, j, wId) = repeatLs[0] ls.append((i, j)) rpLs += repeatLs[::-1] elif len(rpLs) > 1: (i, j, wId) = rpLs[-1] rpLs.remove((i, j, wId)) if ls.__contains__((i, j)): delId = ls.index((i, j)) ls = ls[:delId - 1] (i, j, wId) = rpLs[-1] ls.append((i, j)) rpLs.remove((i, j, wId)) else: return False return True