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.""" if start not in graph: raise KeyError(f"Unknown start node: {start!r}") distances = {node: inf for node in graph} previous: dict[Node, Node | None] = {node: None for node in graph} distances[start] = 0.0 # Counter avoids comparing nodes when distances tie. queue: list[tuple[float, int, Node]] = [(0.0, 0, start)] counter = 1 while queue: distance, _, node = heapq.heappop(queue) if distance != distances[node]: continue # Ignore stale queue entries. for neighbor, weight in graph[node]: if weight < 0: raise ValueError("Dijkstra's algorithm requires non-negative weights") if neighbor not in graph: raise KeyError(f"Unknown neighbor node: {neighbor!r}") candidate = distance + weight if candidate < distances[neighbor]: distances[neighbor] = candidate previous[neighbor] = node heapq.heappush(queue, (candidate, counter, neighbor)) counter += 1 return distances, previous def shortest_path( graph: Graph[Node], start: Node, target: Node ) -> tuple[float, list[Node]]: """Return the distance and node sequence for a shortest path.""" if target not in graph: raise KeyError(f"Unknown target node: {target!r}") distances, previous = dijkstra(graph, start) if distances[target] == inf: return inf, [] path: list[Node] = [] current: Node | None = target while current is not None: path.append(current) current = previous[current] path.reverse() return distances[target], path def main() -> None: graph = { "A": [("B", 4), ("C", 1)], "B": [("D", 1)], "C": [("B", 2), ("D", 5)], "D": [], "E": [], } assert shortest_path(graph, "A", "D") == (4.0, ["A", "C", "B", "D"]) assert shortest_path(graph, "A", "E") == (inf, []) print(shortest_path(graph, "A", "D")) if __name__ == "__main__": main()