如何使用BFS算法获取图中任意两个节点之间的距离(边数)?
我不想将路径信息保存为列表形式(例如下面的代码),以降低代码运行时间。(以获得更好的性能)
def check_distance(self, satrt, end, max_distance):
queue = deque([start])
while queue:
path = queue.popleft()
node = path[-1]
if node == end:
return len(path)
elif len(path) > max_distance:
return False
else:
for adjacent in self.graph.get(node, []):
queue.append(list(path) + [adjacent])