When edges have a cost (kilometers, minutes, euros), the path with the fewest edges is no longer necessarily the best. For non-negative weights, Dijkstra’s algorithm finds the minimum distances from a source: it always expands the closest node among those not yet closed, using a priority queue (heapq).
import heapq
graph = {
"A": [("B", 1), ("C", 4)],
"B": [("C", 2), ("D", 5)],
"C": [("D", 1)],
"D": [],
}
def dijkstra(graph, source):
dist = {node: float("inf") for node in graph}
dist[source] = 0
queue = [(0, source)] # (distance, node): the heap sorts by distance
while queue:
d, u = heapq.heappop(queue)
if d > dist[u]:
continue # stale entry
for v, weight in graph[u]:
if d + weight < dist[v]:
dist[v] = d + weight
heapq.heappush(queue, (dist[v], v))
return dist
print(dijkstra(graph, "A")) # {'A': 0, 'B': 1, 'C': 3, 'D': 4}
- Each heap entry is
(distance, node); Python sorts tuples by distance. - A node can be inserted several times with different distances; when it is popped, if the distance is worse than the stored one, it is discarded (
stale entry). - Cost: O((n + m) log n) with a heap, far better than trying all paths.
- With negative weights Dijkstra fails; you need Bellman-Ford.
- To rebuild the path, store for each node the one you came from (
previous[v] = u) when its distance improves.
You practice it in Weighted shortest path (Dijkstra).