【发布时间】:2020-09-30 11:23:59
【问题描述】:
我正在完成这个 Leetcode 问题:https://leetcode.com/problems/word-search/,我随机选择使用 while 循环和堆栈迭代地实现 DFS,但是在回溯时遇到了一些不便,如果我以递归方式完成问题,我通常不会发生这种情况即我只能考虑实现一个列表 (visited_index) 来跟踪我访问过的索引并弹出值以在回溯时将布尔矩阵 visited 设置回 False。
from collections import defaultdict
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
starting_points = defaultdict(list)
m, n = len(board), len(board[0])
for i in range(m):
for j in range(n):
starting_points[board[i][j]].append((i,j))
start = starting_points[word[0]]
visited = [[False] * n for _ in range(m)]
stack = []
directions = [(1,0), (0,-1), (-1,0), (0,1)]
for s in start:
stack.append((s[0], s[1], 0))
visited_index = [] # EXTRA LIST USED
while stack:
x, y, count = stack.pop()
while len(visited_index) > count:
i, j = visited_index.pop()
visited[i][j] = False # SETTING BACK TO FALSE WHEN BACKTRACKING
if x < 0 or x >= m or y < 0 or y >= n or visited[x][y] or board[x][y] != word[count]:
continue
else:
visited[x][y] = True
visited_index.append((x,y))
if count + 1 == len(word):
return True
for d in directions:
i, j = x + d[0], y + d[1]
stack.append((i,j, count + 1))
else:
stack.clear()
for i in range(m):
for j in range(n):
visited[i][j] = False
return False
我相信,在递归方法中,我可以在函数末尾将visited 布尔值重置为False,而无需使用额外的列表。在使用堆栈进行迭代 DFS 时,是否有人建议不要引入额外的数据结构?
【问题讨论】:
标签: python algorithm stack depth-first-search