def exist(self, board: List[List[str]], word: str) -> bool:
def dfs(i,j,visited,k,board,word):
if not 0<=i <len(board)or not(0<=j <len(board[0])) or board[i][j] != word[k] or visited[i][j]:
return False
if k == len(word)-1:
return True
visited[i][j] = True
res = dfs(i+1,j,visited,k+1,board,word) or dfs(i-1,j,visited,k+1,board,word) or dfs(i,j-1,visited,k+1,board,word) or dfs(i,j+1,visited,k+1,board,word)
visited[i][j] = False
return res
visited = [[False for _ in range(len(board[0]))] for _ in range(len(board))]
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i,j,visited,0,board,word):
return True
return False
矩阵中的路径
最新推荐文章于 2021-03-22 22:14:12 发布