182 - 79 单词搜索
题目
解答
回溯
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not word:
return False
row = len(board)
col = len(board[0])
direction = [(-1, 0), (1, 0), (0, 1), (0, -1)]
def backtrack(i, j, target, visited):
if target == len(word):
return True
for x, y in direction:
tmp_i, tmp_j = x+i, y+j
if 0 <= tmp_i and tmp_i < row and 0 <= tmp_j and tmp_j < col\
and (tmp_i, tmp_j) not in visited and board[tmp_i][tmp_j] == word[target]:
visited.add((tmp_i, tmp_j))
if backtrack(tmp_i, tmp_j, target+1, visited):
return True
visited.remove((tmp_i, tmp_j))
return False
for i in range(row):
for j in range(col):
if board[i][j] == word[0] and backtrack(i, j, 1, {(i, j)}):
return True
return False原地算法
Last updated