描述
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param matrix char字符型二维数组
# @param word string字符串
# @return bool布尔型
#
class Solution:
def dfs(self, matrix:list, m:int, n:int, i:int, j:int, word:str, k:int, flag:list):
if i<0 or j<0 or i>=m or j>=n or word[k] != matrix[i][j] or flag[i][j] == True:
return False
if k == len(word)-1:
return True
flag[i][j] = True
if self.dfs(matrix, m, n, i+1, j, word, k+1, flag) or self.dfs(matrix, m, n, i-1, j, word, k+1, flag) or self.dfs(matrix, m, n, i, j+1, word, k+1, flag) or self.dfs(matrix, m, n, i, j-1, word, k+1, flag):
flag[i][j] = True
return True
flag[i][j] = False
return False
def hasPath(self , matrix: List[List[str]], word: str) -> bool:
# write code here
if len(matrix[0]) == 0:
return False
else:
m = len(matrix)
n = len(matrix[0])
flag = [[False for i in range(n)] for j in range(m)]
for i in range(m):
for j in range(n):
if self.dfs(matrix,m,n,i,j,word,0,flag):
return True
return False