← 中文资源

简体中文版本

用最小堆实现 Dijkstra 最短路径

在非负权有向图上用优先队列计算单源最短路径,跳过过期堆条目,并用 -1 标记不可达节点。

阅读英文原文

题目

给定 n 个节点、若干有向带权边 (u, v, weight) 以及源点 source,计算源点到每个节点的最短距离。源点自身距离为 0,无法到达的节点距离记为 -1。负权边、格式错误的边以及越界的节点编号都必须拒绝。Dijkstra 算法要求所有边权非负,因此负权输入不能静默处理。

  • 输入:节点数 n、有向边 (u, v, weight) 列表、源点 source。
  • 输出:长度为 n 的距离列表,不可达节点用 -1 表示。

解题思路

用邻接表保存每个节点的 (邻居, 权重)。距离数组初始为 None,源点设为 0,并把 (0, source) 放入最小堆。每次弹出当前距离最小的节点,如果弹出的距离大于已记录距离,说明这是过期条目,直接跳过;否则遍历所有出边做松弛,发现更短路径时更新距离并把新条目压入堆。

这种“惰性删除”避免实现 decrease-key:旧条目仍留在堆中,但会被跳过。使用二叉堆时总复杂度为 O((V+E) log V)。Dijkstra 的正确性依赖非负权:一个节点以当前最小 tentative 距离被弹出后,不可能再被更长的路径改进。

参考实现要点

  1. 校验 source 在 0 到 n-1 范围内,n 不能为负数。
  2. 每条边检查长度为 3、端点合法、权重非负。
  3. distances 用 None 表示未访问,源点设为 0,堆初始为 [(0, source)]。
  4. 弹出时若 current 大于 distances[node],说明条目过期,continue。
  5. 松弛成功时更新 distances 并 heappush,最后把 None 转成 -1。

常见错误

  • 使用普通队列而不是最小堆,算法退化为 BFS,完全忽略权重。
  • 不跳过过期堆条目,虽然结果仍正确,但会重复处理大量旧状态。
  • 把不可达节点初始化为 0,最终结果与真实距离混淆。
  • 接受负权边,Dijkstra 的贪心前提被破坏,可能得到错误答案。

验证方式

运行两个公开样例,确认输出 [0, 3, 1, 4] 和 [-1, -1, 0]。再测试直达边很贵但多跳更便宜的图、平行边、零权自环、非连通分量和单节点图。确认负权输入会抛出异常。对小规模随机图,可用 Bellman-Ford 或 Floyd-Warshall 作为对照,比较所有节点距离是否一致。

代码示例

import heapq


def dijkstra(n, edges, source):
    if n < 0 or not 0 <= source < n:
        raise ValueError("source must be a valid node")
    graph = [[] for _ in range(n)]
    for edge in edges:
        if len(edge) != 3:
            raise ValueError("each edge must contain u, v, and weight")
        u, v, weight = edge
        if not (0 <= u < n and 0 <= v < n):
            raise ValueError(f"edge endpoint out of range: {edge!r}")
        if weight < 0:
            raise ValueError("Dijkstra requires non-negative weights")
        graph[u].append((v, weight))

    distances = [None] * n
    distances[source] = 0
    heap = [(0, source)]
    while heap:
        current, node = heapq.heappop(heap)
        if distances[node] is not None and current > distances[node]:
            continue
        for neighbor, weight in graph[node]:
            candidate = current + weight
            if distances[neighbor] is None or candidate < distances[neighbor]:
                distances[neighbor] = candidate
                heapq.heappush(heap, (candidate, neighbor))
    return [distance if distance is not None else -1 for distance in distances]


if __name__ == "__main__":
    print(dijkstra(4, [(0, 1, 4), (0, 2, 1), (2, 1, 2), (1, 3, 1)], 0))
    print(dijkstra(3, [(0, 1, 5)], 2))