利用 dfs 进行搜索,避免重复访问加入辅助数组 vistited,注意在每次路径递归失败后,将辅助数组的值置回初始值。
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param board string字符串一维数组
# @param word string字符串
# @return bool布尔型
#
class Solution:
def exist(self , board: List[str], word: str) -> bool:
# write code here
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[i])):
if board[i][j] == word[0]:
if self.search(i, j, len(board), len(board[i]), visited, board, word[1:]):
return True
return False
def search(self, x, y, m, n, visited, board, word):
if not word:
return True
visited[x][y] = True
direation = [(-1, 0), (0, 1), (1, 0), (0, -1)]
for i, j in direation:
xi, yi = x + i, y + j
if 0 <= xi < m and 0 <= yi < n and not visited[xi][yi] and board[xi][yi] == word[0]:
if self.search(xi, yi, m, n, visited, board, word[1:]):
return True
visited[x][y] = False
return False