← 中文资源

简体中文版本

Python Dijkstra 最短路径

用 heapq 优先队列实现 Dijkstra,计算加权图从起点到各节点的最短距离。

阅读英文原文

题目

编写函数接收加权邻接表与起点,返回起点到所有节点的最短距离。输入契约:node -> [(neighbor, weight)] 的字典与起点;输出契约:节点到最短距离的字典。公开样例 A 到 B 权重 1、A 到 C 权重 4、B 到 C 权重 2,期望 {"A":0,"B":1,"C":3}。隐藏测试覆盖孤立起点与单边图。

解题思路

维护 distances 字典,初始化为无穷大、起点为 0;用最小堆保存 (距离, 节点)。每次弹出当前最短的节点;若距离已过期则跳过;否则松弛所有邻居,发现更短路径就更新并入堆。

参考实现要点

distances = {node: float("inf") for node in graph},起点置 0;pq = [(0, start)];循环 heappop,若 dist > distances[node] 则 continue;对 graph.get(node, []) 中每个 (neighbor, weight) 计算 new_dist,较小时更新并入堆。返回 distances。

常见错误

原文指出不跳过已处理节点(dist > distances[node])会造成重复处理并可能得到错误结果。另一个坑是忽略算法的前提:背景明确限定非负权重图;若出现负权边,已弹出节点仍可能被更短路径更新,结果不再正确。

验证方式

在 Python 3 中用样例图运行,断言距离;再测 {"A":[]} 与单边图两个隐藏用例;另外给多条等长路径,确认输出稳定为最短值。

代码示例

import heapq

def dijkstra(graph, start):
    distances = {node: float("inf") for node in graph}
    distances[start] = 0
    pq = [(0, start)]
    while pq:
        dist, node = heapq.heappop(pq)
        if dist > distances[node]:
            continue
        for neighbor, weight in graph.get(node, []):
            new_dist = dist + weight
            if new_dist < distances[neighbor]:
                distances[neighbor] = new_dist
                heapq.heappush(pq, (new_dist, neighbor))
    return distances