题解 | Python3 | 高可读性一看就会版
矩阵中的路径
https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param matrix char字符型二维数组 # @param word string字符串 # @return bool布尔型 # # global def X = 0 Y = 1 class Solution: def hasPath(self, matrix: List[List[str]], word: str) -> bool: # write code here if not matrix or not word: return False # init self.__size = len(matrix[0]), len(matrix) self.__target = word self.__matrix = matrix self.__visited = [[False for _ in range(self.__size[X])] for _ in range(self.__size[Y])] # prog for ix in range(self.__size[X]): for iy in range(self.__size[Y]): if self.tryFindPath((ix, iy), 0): return True return False def tryFindPath(self, pos: tuple, idxof_target: int) -> bool: # all word is match successfully if idxof_target >= len(self.__target): return True # else word is not fully match , require continue: # x: out of matrix if self.positionOutOfRange(pos): return False # x: already visited if self.__visited[pos[Y]][pos[X]]: return False # x: word not match curr_match_word = self.__target[idxof_target] if self.__matrix[pos[Y]][pos[X]] != curr_match_word: return False # √: when execute here, current word is successfully matched. print(f"√: matched {curr_match_word} in {pos}") self.__visited[pos[Y]][pos[X]] = True # next step, we try to match next word: if ( (self.tryFindPath((pos[X] + 1, pos[Y]), idxof_target + 1)) or (self.tryFindPath((pos[X] - 1, pos[Y]), idxof_target + 1)) or (self.tryFindPath((pos[X], pos[Y] + 1), idxof_target + 1)) or (self.tryFindPath((pos[X], pos[Y] - 1), idxof_target + 1)) ): return True else: self.__visited[pos[Y]][pos[X]] = False return False def positionOutOfRange(self, case_pos: tuple) -> bool: if case_pos[X] < 0 or case_pos[Y] < 0: return True if case_pos[X] >= self.__size[X] or case_pos[Y] >= self.__size[Y]: return True return False