Sub topic 12
Shortest paths in weighted graphs with Dijkstra's algorithm
This chapter assumes you can read the adjacency-list dictionary from earlier chapters, use a heap with heapq, and reason about big-O costs. It covers shortest paths from one source in a weighted graph. Here "shortest" means the smallest total edge weight, not the fewest edges.
Why BFS is not enough
Breadth-first search finds the path with the fewest edges. In a weighted graph, that path can be expensive. Take a direct edge A to B with weight 4, and a two-edge route A to C to B with weights 1 and 2. BFS prefers the direct edge (4). The two-edge route costs only 3.
The idea
Dijkstra's algorithm keeps a best-known distance for each vertex. It then repeats these steps:
- Take the unfinished vertex with the smallest known distance from a priority queue.
- Treat that distance as final.
- Relax each outgoing edge. If going through this vertex gives a neighbor a shorter distance, record it and push the neighbor onto the queue.
Step 2 is correct only when no edge weight is negative. Every other route to that vertex must pass through an unfinished vertex that is at least as far away. Adding more non-negative weights cannot make that route shorter.
Implementation
The code below is complete and runnable. It reuses add_edge from the earlier chapter.
import heapq
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
def dijkstra(graph, source):
dist = {source: 0}
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
for v, w in graph[u].items():
new_dist = d + w
if new_dist < dist.get(v, float("inf")):
dist[v] = new_dist
heapq.heappush(heap, (new_dist, v))
return dist
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
print(dijkstra(weighted, "A")) # {'A': 0, 'B': 3, 'C': 1}Tracing the run
- Pop
(0, A). Set B to 4 and C to 1. - Pop
(1, C). The route A, C, B costs 1 + 2 = 3, which beats 4. Update B to 3 and push(3, B). - Pop
(3, B). Its neighbors cannot be improved. - Pop the stale entry
(4, B). Since 4 >dist[B](3), thecontinueline skips it.
Python's heapq cannot lower the priority of an item already in the heap. The code pushes a new entry instead and discards stale ones when they surface. This is called lazy deletion.
Cost
Each edge can cause at most one push, so the heap holds at most E entries. Each push or pop costs O(log E). The total is O((V + E) log V) in the usual analysis. A vertex missing from the result is unreachable from the source.
Common errors
- Negative edge weights. The "first pop is final" argument breaks. The code may return wrong distances, or do far more work than expected. With a negative cycle, "shortest" has no meaning. Use Bellman-Ford for graphs with negative edges.
- Skipping the stale-entry check. Without
if d > dist[u]: continue, the output stays correct but each stale entry is processed again, which wastes time. - Expecting the path itself. The function returns distances only. To recover routes, store a
parentdictionary and setparent[v] = uwhenever you updatedist[v]. - Using it on unweighted graphs. BFS gives the same answer with less overhead, so prefer it there.
Exercise
Add an edge from D to A with weight 1 to the directed graph A to B (weight 2) and A to C (weight 5), then run dijkstra(graph, "A"). What does the result contain, and why is D absent?
Show answer
The result is {'A': 0, 'B': 2, 'C': 5}. D has an edge into A, but no path leads from A to D, so D is unreachable from the source and never receives a distance.