实现说明
整个示例围绕函数 dijkstra组织。
while heap 承担全部的逐项处理。
使用要点
- 调用方只需要
dijkstra——其余都是内部实现。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件在加载时定义 dijkstra。
主签名形如 def dijkstra(graph, start)
代码示例
import heapq
def dijkstra(graph, start):
dist = {n: float("inf") for n in graph}
dist[start] = 0
heap = [(0, start)]
while heap:
d, node = heapq.heappop(heap)
if d > dist[node]:
continue
for neighbor, weight in graph.get(node, []):
nd = d + weight
if nd < dist[neighbor]:
dist[neighbor] = nd
heapq.heappush(heap, (nd, neighbor))
return dist