题解 | #矩阵中的路径#发布一个Python版本的题解
矩阵中的路径
https://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param matrix char字符型二维数组 # @param word string字符串 # @return bool布尔型 # class Solution: def hasPath(self , matrix: List[List[str]], word: str) -> bool: # write code here def dfs(i,j,index): if i<0 or i>=len(matrix) or j<0 or j>=len(matrix[0]) or matrix[i][j]!=word[index]: return False if index==len(word)-1 and matrix[i][j]==word[index]: return True temp=matrix[i][j] matrix[i][j]="" res=dfs(i+1,j,index+1) or dfs(i-1,j,index+1) or dfs(i,j+1,index+1) or dfs(i,j-1,index+1) matrix[i][j]=temp return res m,n=len(matrix),len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j]==word[0]: if dfs(i,j,0): return True return False