题解 | #矩阵中的路径#
矩阵中的路径
http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param matrix char字符型二维数组
# @param word string字符串
# @return bool布尔型
#
class Solution:
def dfs(self, m,n, matrix, visited, word, k):
if k >= len(word):
return True
if m < 0 or n < 0 or m >= len(matrix) or n >= len(matrix[0]) or visited[m][n] == 1:
return False
print(m, n, k, word[k])
if matrix[m][n] == word[k]:
visited[m][n] = 1
if self.dfs(m+1,n,matrix,visited, word, k+1) or self.dfs(m-1,n,matrix,visited, word, k+1) or self.dfs(m,n+1,matrix,visited, word, k+1) or self.dfs(m,n-1,matrix,visited, word, k+1):
return True
else:
visited[m][n] = 0
return False
return False
def hasPath(self , matrix , word ):
# write code here
l = len(matrix)
w = len(matrix[0])
for i in range(l):
for j in range(w):
visited = multilist = [[0 for col in range(w)] for row in range(l)]
if matrix[i][j] == word[0]:
res = self.dfs(i,j, matrix, visited, word, 0)
# print(matrix[i][j], res)
if res:
return True
return False