我已经在Python3中实现了BFS,以在迷宫中查找从开始坐标到结束坐标的所有唯一路径,但是我不确定检查给定迭代中是否已访问节点的最有效方法。
我尝试了似乎是跟踪先前遍历的节点的标准列表实现以及OrderedDict实现。我的问题是在“ valid_neighbors”步骤中,并检查遍历路径中是否已存在邻居。
使用标准列表实现,查找将为O(n),其中n是遍历路径的长度。使用OrderedDict实现时(根据我的理解),查找应该大致为O(1),但每次迭代都会重新整理OrderedDict,这是一项昂贵的O(n)操作。
from collections import deque, OrderedDict, namedtuple
from typing import List
Coordinate = namedtuple('Coordinate', ('x', 'y'))
def bfs_matrix(maze: List[List[int]],
start: Coordinate,
end: Coordinate) -> List[List[Coordinate]]:
"""First path is the shortest."""
queue: deque[OrderedDict[Coordinate, Coordinate]] = deque()
queue.append(OrderedDict({start: start}))
paths: List[OrderedDict[Coordinate, Coordinate]] = []
while queue:
path: OrderedDict[Coordinate, Coordinate] = queue.popleft()
# path: List[Coordinate] = queue.popleft()
# node: Coordinate = path[-1]
node: Coordinate = next(reversed(path))
# visited = set(path)
if node == end:
paths.append(path)
else:
neighbors = map(Coordinate,
(node.x-1, node.x+1, node.x, node.x),
(node.y, node.y, node.y-1, node.y+1))
valid_neighbors = [C for C in neighbors if
0 <= C.x < len(maze) and
0 <= C.y < len(maze[0]) and
C not in path]
for neighbor in valid_neighbors:
# new_path: List[Coordinate] = list(path)
new_path: OrderedDict[Coordinate, Coordinate] = OrderedDict(path)
# new_path.append(neighbor)
new_path[neighbor] = neighbor
queue.append(new_path)
return paths
我使用此算法获得了所有唯一路径,并且看起来运行相当快,但是我想知道是否有更好的方法来检查新遍历的节点的成员资格条件。