解题思路:dfs + 回溯 + 剪枝,如果当前位置[i][j]
满足条件,就继续向下dfs,如果不满足就回溯visited[i][j]=0
,再尝试其他的点
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if word == "":
return True
row = len(board)
if row == 0:
return False
col = len(board[0])
if col == 0:
return False
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
visited = [[0] * col for i in range(row)]
def traceback(word, x, y):
if word == "":
return True
for i in range(4):
new_x = x + dx[i]
new_y = y + dy[i]
if 0 <= new_x < col and 0 <= new_y < row and visited[new_y][new_x] == 0 and board[new_y][new_x] == word[0]:
visited[new_y][new_x] = 1
if traceback(word[1:], new_x, new_y):
return True
visited[new_y][new_x] = 0
return False
for i in range(row):
for j in range(col):
if board[i][j] == word[0] and visited[i][j] == 0:
visited[i][j] = 1
if traceback(word[1:], j, i):
return True
visited[i][j] = 0
return False