【发布时间】:2020-09-06 15:31:26
【问题描述】:
在阅读 Dijkstra 算法时,我发现您应该实现一个最小堆。我尝试实现一个最小堆并且该算法有效,但是当我不使用最小堆函数而只是弹出索引 0 处的顶点时它也有效。
我很困惑,当我们无论如何都要探索堆中的所有顶点时,为什么我们总是需要选择具有最小距离的顶点来进行下一步探索。
例如:
from heapq import heappop, heappush
from math import inf
graph = {
'A': [('B', 10), ('C', 3)],
'C': [('D', 2)],
'D': [('E', 10)],
'E': [('A', 7)],
'B': [('C', 3), ('D', 2)]
}
def dijkstras(graph, start):
distances = {}
for vertex in graph:
distances[vertex] = inf
distances[start] = 0
vertices_to_explore = [(0, start)]
while vertices_to_explore:
current_distance, current_vertex = heappop(vertices_to_explore) # this piece of code
#current_distance, current_vertex = vertices_to_explore.pop(0) # vs. this piece of code
for neighbor, edge_weight in graph[current_vertex]:
new_distance = current_distance + edge_weight
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
heappush(vertices_to_explore, (new_distance, neighbor))
return distances
distances_from_d = dijkstras(graph, 'D')
print("\n\nShortest Distances: {0}".format(distances_from_d))
为什么在 pop(0) 工作时使用 heappop... 是因为运行时间?如果是,为什么它跑得更快?
谢谢
【问题讨论】:
-
运行时间可以用编译器测量,也许你应该测量一些东西。如果它们在时间上有所不同,那么它们的工作方式就真的不一样了。他们可能有相同的结果,但我敢打赌,你一个专门研究堆,而另一个则处理列表。