Shortest Path Algorithms (DSA #21)
GPS routes, network packet routing, and flight-price search are all the same question: what is the cheapest way from here to there when every edge has a cost? BFS answers “fewest hops”, but the moment edges have different weights, fewest hops is the wrong answer — a two-hop flight can cost more than a five-hop one. This chapter covers the three shortest-path algorithms that matter: Dijkstra, Bellman-Ford, and A*.
The problem
Given a weighted graph and a source, find the minimum total edge weight to every vertex (or to a target). The assumption about edge weights decides the algorithm:
| Algorithm | Handles | Time |
|---|---|---|
| BFS | unweighted (unit edges) | \(O(V + E)\) |
| Dijkstra | non-negative weights | \(O((V + E)\log V)\) |
| Bellman-Ford | negative weights, detects negative cycles | \(O(VE)\) |
| A* | non-negative + heuristic, one target | like Dijkstra, often faster |
Dijkstra: greedy relaxation
Dijkstra’s insight: if all edges are non-negative, the closest unfinalised vertex is already at its final distance. Repeatedly extract the closest vertex and relax its outgoing edges — if going through it improves a neighbour’s distance, update it.
The frontier is a min-heap (Chapter 11) keyed by tentative distance.
import heapq
def dijkstra(graph, source):
dist = {v: float("inf") for v in graph}
dist[source] = 0
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]: # stale heap entry
continue
for v, w in graph[u]: # relax neighbours
if d + w < dist[v]:
dist[v] = d + w
heapq.heappush(heap, (dist[v], v))
return dist
Two details make it correct: the if d > dist[u]: continue guard skips outdated heap entries (Dijkstra pushes duplicates rather than decreasing a key), and the algorithm only works because weights are non-negative — a negative edge could make an already-finalised vertex improve later, which the greedy choice forbids.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, circle, minimum size=0.72cm, font=\small\bfseries, inner sep=0pt},
a/.style={->, thick}]
\node[n, fill=green!25] (s) at (0,0) {A:0};
\node[n, fill=blue!12] (b) at (2.0,0.9) {B:4};
\node[n, fill=blue!12] (c) at (2.0,-0.9) {C:2};
\node[n, fill=orange!22] (d) at (4.0,0) {D:5};
\draw[a] (s) -- node[above, font=\scriptsize] {4} (b);
\draw[a] (s) -- node[below, font=\scriptsize] {2} (c);
\draw[a] (b) -- node[above, font=\scriptsize] {1} (d);
\draw[a] (c) -- node[below, font=\scriptsize] {5} (d);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.0,-1.4) {relax via C: D=2+5=7, then via B: D=4+1=5};
\end{tikzpicture}
With a binary heap the cost is \(O((V + E) \log V)\); with a Fibonacci heap it improves to \(O(E + V \log V)\), but the constant is large and rarely used in practice.
Bellman-Ford: tolerate negative edges
Bellman-Ford relaxes every edge \(V-1\) times. After \(i\) rounds, it has found all shortest paths using at most \(i\) edges, so \(V-1\) rounds suffice. It is slower than Dijkstra but handles negative weights and can detect negative cycles.
def bellman_ford(edges, n, source):
dist = [float("inf")] * n
dist[source] = 0
for _ in range(n - 1): # V-1 rounds
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed: # converged early
break
for u, v, w in edges: # one more round
if dist[u] + w < dist[v]:
return None # negative cycle reachable
return dist
A negative cycle reachable from the source means “shortest path” is undefined (you can loop forever to reduce cost), and the extra pass detects it.
A*: Dijkstra with a goal
Dijkstra explores in all directions. If you only care about one target and you have a heuristic that estimates the remaining distance (e.g. straight-line distance on a map), A* prioritises promising vertices and reaches the target faster.
\[ f(v) = g(v) + h(v) \]
where \(g(v)\) is the known cost from the source and \(h(v)\) is the estimated cost to the target. The heuristic must be admissible — never overestimate the true remaining cost — for A* to be optimal.
def astar(graph, source, target, heuristic):
import heapq
g = {source: 0}
heap = [(heuristic(source), source)]
while heap:
_, u = heapq.heappop(heap)
if u == target:
return g[u]
for v, w in graph[u]:
tentative = g[u] + w
if tentative < g.get(v, float("inf")):
g[v] = tentative
heapq.heappush(heap, (tentative + heuristic(v), v))
return None
With \(h = 0\), A* becomes Dijkstra; with a perfect heuristic it walks straight to the goal. GPS routing is A* on a road graph with the straight-line heuristic.
Choosing the algorithm
- Unweighted graph? BFS — simpler and faster than Dijkstra.
- Non-negative weights, all targets? Dijkstra.
- Negative weights? Bellman-Ford (which also detects negative cycles).
- One target plus a good heuristic? A*.
- All-pairs shortest paths? Floyd-Warshall, \(O(V^3)\), for small dense graphs.
# Floyd-Warshall: all-pairs in O(V^3)
def floyd_warshall(dist):
n = len(dist)
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
Pitfalls
- Running Dijkstra with negative edges. It can return a wrong “finalised” distance; use Bellman-Ford instead.
- Forgetting the stale-entry guard. Without
if d > dist[u]: continue, old heap entries cause redundant work and can produce wrong results in some variants. - Non-admissible A* heuristic. An overestimating heuristic breaks optimality; the route may be shorter but not cheapest.
- Ignoring disconnected vertices. Distances stay infinity; handle unreachable targets explicitly.
- Confusing shortest path with fewest edges. On weighted graphs, fewest hops is not cheapest.
- Not detecting negative cycles. A “shortest path” through a negative cycle does not exist; Bellman-Ford’s extra pass is essential.
Why does Dijkstra require non-negative weights, and how does Bellman-Ford handle negatives? What makes an A* heuristic admissible?
ASolution
Dijkstra finalises the closest vertex assuming it cannot later improve; a negative edge could improve an already-finalised vertex, breaking that assumption. Bellman-Ford relaxes all edges \(V-1\) times, so it accommodates negatives and detects negative cycles with one extra pass. A heuristic is admissible if it never overestimates the true remaining cost, which keeps A* optimal.
Next: Minimum Spanning Trees (DSA #22) — connecting everything for the least total cost.