Sub topic 12
Shortest paths in weighted graphs with Dijkstra's algorithm
This chapter assumes you can read the adjacency-list representation from earlier chapters (a dictionary that maps each vertex to a dictionary of neighbors and weights). It also assumes you know how a priority queue works, and that you remember breadth-first search (BFS) and big-O notation.
The problem
A shortest path between two vertices is the path whose edge weights add up to the smallest total. The single-source shortest path problem asks for the shortest distance from one source vertex to every other vertex.
BFS already solves this when every edge costs the same, because it visits vertices in order of edge count. Weights break that. In the graph below, the direct edge A to B has weight 4, but the two-edge route A to C to B costs only 1 + 2 = 3. Fewer edges does not mean lower cost.
Dijkstra's algorithm solves this problem when every edge weight is zero or positive.
The idea
Dijkstra's algorithm keeps a tentative distance for each vertex. This is the best known cost so far, and it starts at infinity for everything except the source, which starts at 0. The algorithm repeats two steps:
- Take the vertex with the smallest tentative distance that has not been finished yet.
- Relax each of its outgoing edges. To relax the edge from u to v with weight w, compute
dist[u] + w. If that is smaller than the currentdist[v], replace it.
Once a vertex is taken in step 1, its distance is final. This is the core claim, and it holds only because weights are non-negative. Any other route to that vertex must pass through some vertex that has a tentative distance at least as large. Adding more non-negative edges cannot make that route cheaper.
A priority queue (a min-heap) makes step 1 fast. Python's heapq has no "decrease key" operation. The usual workaround is to push a new (distance, vertex) entry whenever a distance improves, and to skip stale entries when they are popped.
The implementation
This version returns both the distances and a prev dictionary. The prev dictionary records which vertex each shortest path came from, so you can rebuild the route itself.
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}
prev = {}
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale entry: a shorter route was already found
for v, w in graph[u].items():
new_dist = d + w
if new_dist < dist.get(v, float("inf")):
dist[v] = new_dist
prev[v] = u
heapq.heappush(heap, (new_dist, v))
return dist, prev
def path_to(prev, source, target):
if target != source and target not in prev:
return None # target is unreachable
path = [target]
while path[-1] != source:
path.append(prev[path[-1]])
path.reverse()
return path
weighted = {}
add_edge(weighted, "A", "B", 4)
add_edge(weighted, "A", "C", 1)
add_edge(weighted, "C", "B", 2)
dist, prev = dijkstra(weighted, "A")
print(dist) # {'A': 0, 'C': 1, 'B': 3}
print(path_to(prev, "A", "B")) # ['A', 'C', 'B']The distances are the same as in the earlier chapter's example. A dictionary prints in insertion order, so C appears before B here, because B is first set to 4 and only later improved to 3. Only the values matter.
Tracing the example
| Step | Popped | Action | `dist` after the step |
|---|---|---|---|
| 0 | none | Start with the source | A=0 |
| 1 | (0, A) | Relax A to B: 0+4=4. Relax A to C: 0+1=1 | A=0, B=4, C=1 |
| 2 | (1, C) | Relax C to B: 1+2=3, which beats 4 | A=0, B=3, C=1 |
| 3 | (3, B) | Relax B to A: 3+4=7, which does not beat 0 | unchanged |
| 4 | (4, B) | Stale: 4 > dist[B]=3, so it is skipped | unchanged |
At step 3 the heap held both (3, B) and (4, B). The older entry is never removed. The check d > dist[u] discards it when it finally reaches the front.
Cost
Each edge is relaxed at most once, because each vertex is processed once when it is popped with its final distance. A relaxation can push one heap entry, so the heap holds at most E entries. Each push or pop costs O(log E), which is O(log V) because E is at most V². The total is O(E log V), or equivalently O((V + E) log V) when you count the work of visiting each vertex.
The adjacency list matters here. With an adjacency matrix, scanning a vertex's neighbors costs O(V) each time, so a matrix-based version costs at least O(V²). For a dense graph, where E is close to V², that is actually competitive. The simple version scans an array for the minimum instead of using a heap and also runs in O(V²).
Unreachable vertices and edge cases
- Unreachable vertices. A vertex that cannot be reached from the source never gets an entry in
dist. Usedist.get(v, float("inf"))when you want an explicit infinity, and treat a missing key as "no path". - Source equals target. The distance is 0 and the path is just
[source].path_tohandles this. - Zero-weight edges. These are fine. Ties are broken by comparing the vertex names inside the tuples, so vertices in the heap must be comparable. If your vertices are arbitrary objects, add a counter as a tie-breaker:
(dist, counter, vertex). - Directed graphs. The code works unchanged. Store each edge in one direction with
directed=True, and the algorithm follows only outgoing edges. - Parallel edges. A dictionary of dictionaries keeps one weight per pair. If a graph has several edges between the same two vertices, store the minimum, because only the cheapest one can matter.
- Early exit. If you only need the distance to one target, return as soon as that target is popped. Its distance is already final.
When Dijkstra does not apply
Dijkstra's correctness proof requires non-negative edge weights. A negative edge breaks the claim that a finished vertex can never be improved.
Consider a directed graph with A to B (weight 2), A to C (weight 5), and C to B (weight -4). The true shortest distance to B is 5 - 4 = 1. A classic implementation finalizes B at distance 2 when it pops B before C, and it never revisits B, so it returns the wrong answer.
The lazy-heap code above happens to push B again when it relaxes C to B, so on this tiny input it would end with the correct distance 1. Do not rely on that. With negative edges it can reprocess vertices many times, and the running time can grow exponentially in bad cases. If the graph has a negative cycle (a cycle whose weights sum below zero), the shortest distance is not defined at all, and the loop would run forever.
Use a different tool when weights can be negative:
| Situation | Better choice |
|---|---|
| All edges have equal weight | BFS |
| Non-negative weights, one source | Dijkstra |
| Negative weights, no negative cycles | Bellman-Ford |
| Negative cycle may exist | Bellman-Ford, which detects the cycle |
| Weighted DAG | Process vertices in topological order and relax each edge once |
Common mistakes
- Marking a vertex as seen when it is queued, as BFS does. In BFS the first time you see a vertex is the best time. In Dijkstra the first distance you find can be improved later, so finality only comes when the vertex is popped.
- Forgetting the stale-entry check. Without
if d > dist[u]: continue, the result is still correct but the algorithm does redundant work, and in dense graphs that can be a large slowdown. - Using a plain queue instead of a priority queue. A FIFO queue processes vertices in discovery order, not in distance order. This is BFS, not Dijkstra.
- Treating a missing key as zero. An unreachable vertex has no distance. Reading
dist[v]for it raises aKeyError, which is the correct signal.
Exercise
In the graph built with addedge(g, "S", "X", 2, directed=True), addedge(g, "S", "Y", 7, directed=True), addedge(g, "X", "Y", 3, directed=True) and addedge(g, "Z", "S", 1, directed=True), what does dijkstra(g, "S")[0] return, and what is path_to(prev, "S", "Y")? Why is Z missing from the result?
Show answer
The distances are S=0, X=2 and Y=5 (the route S to X to Y costs 2 + 3 = 5, which beats the direct edge of 7). The path to Y is ['S', 'X', 'Y']. Z is missing because its only edge points into S, so no path leads from S to Z, and an unreachable vertex never receives a distance entry.
Exercise
Why does Dijkstra's algorithm fail on a graph with a negative edge, and which algorithm should you use instead?
Show answer
Dijkstra treats a vertex's distance as final when it is popped from the heap, because any other route would have to add non-negative weights to a distance that is already at least as large. A negative edge can make a later route cheaper, so the finalized distance may be wrong. Use Bellman-Ford, which tolerates negative edges and detects negative cycles.