from __future__ import annotations import heapq from collections.abc import Hashable, Mapping, Sequence from math import inf from typing import TypeVar Node = TypeVar("Node", bound=Hashable) Graph = Mapping[Node, Sequence[tuple[Node, float]]] def dijkstra( graph: Graph[Node], start: Node ) -> tuple[dict[Node, float], dict[Node, Node | None]]: """Return shortest distances and predecessors from start.""" nodes = set(graph) nodes.add(start) nodes.update(neighbor for edges in graph.values() for neighbor, _ in edges) distances = {node: inf for node in nodes} previous: dict[Node, Node | None] = {node: None for node in nodes} distances[start] = 0.0 # The counter prevents comparisons between nodes when distances tie. counter = 0 queue: list[tuple[float, int, Node]] = [(0.0, counter, start)] while queue: distance, _, node = heapq.heappop(queue) if distance != distances[node]: continue # Ignore stale queue entries. for neighbor, weight in graph.get(node, ()): if weight < 0: raise ValueError("Dijkstra's algorithm requires non-negative weights") candidate = distance + weight if candidate < distances[neighbor]: distances[neighbor] = candidate previous[neighbor] = node counter += 1 heapq.heappush(queue, (candidate, counter, neighbor)) return distances, previous def shortest_path( previous: Mapping[Node, Node | None], start: Node, target: Node ) -> list[Node]: """Reconstruct a path; return an empty list when target is unreachable.""" path: list[Node] = [] current: Node | None = target while current is not None: path.append(current) if current == start: return list(reversed(path)) current = previous.get(current) return [] def main() -> None: graph = { "A": [("B", 4), ("C", 1)], "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": [], "E": [], } distances, previous = dijkstra(graph, "A") assert distances["D"] == 4 assert shortest_path(previous, "A", "D") == ["A", "C", "B", "D"] assert distances["E"] == inf assert shortest_path(previous, "A", "E") == [] if __name__ == "__main__": main()