Shortest Paths (BFS, Dijkstra, Bellman-Ford)
Choose by edge weights: BFS when all edges cost the same, Dijkstra with a min-heap when weights are non-negative, Bellman-Ford when some are negative or you must detect a negative cycle.
How it works
- All three relax edges: if
dist[u] + w < dist[v], lowerdist[v]and record u as its parent. - Dijkstra pops the closest node from a min-heap; with no negative edges, that distance is final.
heapqhas no decrease-key: push a new entry on each improvement and skip stale ones when popped.- Bellman-Ford relaxes every edge V − 1 times; any further improvement means a negative cycle.
- Only 0/1 weights: 0-1 BFS with a deque. A DAG: relax in topological order.
Check yourself
Answer to mark it learned; your answers aren't scored.
A 1000×1000 grid: moving into a cell costs between 0 and 9. Find the minimum total cost from the top-left to the bottom-right cell. What do you use?
Go deeper
Solve it in Python 9
- Budget trip with a stop limitmedium
- Count the fastest routesmedium
- Many distance queries on a small mapmedium
- Fewest walls to break throughmedium
- Signal arrival timemedium
- Route with the smallest worst stepmedium
- A toll loop that pays youmedium
- Cheapest drive with a limited tankhard
- Second fastest arrivalhard
Full explanation
All three compute distances from one source by relaxing edges: if dist[u] + w < dist[v], then dist[v] = dist[u] + w. They differ in which weights they tolerate.
- BFS: every edge costs 1. A queue visits nodes in hop order, so the first visit is the shortest. O(V + E).
- Dijkstra: weights ≥ 0. Pop the closest unsettled node from a min-heap and relax its edges. With no negative edge, nothing found later can be cheaper, so a popped distance is final. O((V + E) log V) with a binary heap.
- Bellman-Ford: any weights. Relax every edge V − 1 times (a shortest path has at most V − 1 edges). If one more pass still improves something, a negative cycle is reachable. O(V·E).
Signals: "minimum cost, time or steps from A", grids with move costs, network delay, cheapest route with at most k stops. Shortcuts: only 0/1 weights → 0-1 BFS with a deque; a DAG → relax in Topological sort order, O(V + E).
Code Dijkstra (lazy heap) and Bellman-Ford
import heapq
def dijkstra(adj, src): # adj[u] = [(v, w), ...], all w >= 0
dist = {src: 0}
heap = [(0, src)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale entry: heapq has no decrease-key
for v, w in adj.get(u, []):
nd = d + w
if nd < dist.get(v, float("inf")):
dist[v] = nd # relax
heapq.heappush(heap, (nd, v))
return dist
def bellman_ford(n, edges, src): # edges = [(u, v, w)], w may be < 0
dist = [float("inf")] * n
dist[src] = 0
for _ in range(n - 1): # a shortest path has at most n-1 edges
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in edges: # still improving? negative cycle
if dist[u] + w < dist[v]:
raise ValueError("negative cycle reachable from src")
return dist
# Unweighted graph? BFS with collections.deque gives the same answer in O(V + E).Real example
Network delay time. n servers, directed links (u, v, ms) with non-negative latency; a signal starts at server k. When has every server received it? Run Dijkstra from k; the answer is the largest distance, or −1 if some server is unreachable. Links 2→1, 2→3 and 3→4 at 1 ms each, source 2: distances 1, 1 and 2, so the answer is 2 ms. O((V + E) log V).
Trade-offs +3 · −3
+ You gain
- One idea, relaxation, covers most "minimum cost" problems.
- Dijkstra scales to large sparse graphs: O((V + E) log V).
- Bellman-Ford handles negative weights and detects negative cycles.
− You pay
- A negative edge breaks Dijkstra: a visited-set version returns wrong distances silently; the lazy one loses its time bound.
- Bellman-Ford's O(V·E) is too slow for large graphs.
- Python's
heapqhas no decrease-key, so the heap carries stale entries.
Use it when
"Minimum total cost, time or steps" from a source: routing, network delay, grids with move costs, cheapest route with at most k stops (Bellman-Ford for k + 1 rounds).
Avoid it when
You only need reachability or connectivity (BFS/DFS or Union-Find (Disjoint Set Union)), or all-pairs distances on a big graph. On a DAG, skip the heap and relax in topological order.
Numbers to know 5
- BFS: O(V + E). Dijkstra with a binary heap: O((V + E) log V).
- Bellman-Ford: O(V·E), V − 1 rounds plus one round to detect a negative cycle.
- DAG shortest paths: O(V + E) in topological order, negative weights allowed.
- 0-1 BFS: O(V + E), pushing 0-cost edges to the front of the deque.
- Floyd-Warshall, all pairs: O(V³) time, O(V²) space.
Common pitfalls 4
- Trusting Dijkstra because there is no negative cycle: a single negative edge already breaks it.
- No stale check (
if d > dist[u]: continue): old heap entries get re-expanded and time balloons. - Marking nodes visited when pushed instead of when popped: locks in a non-optimal distance.
- BFS with
list.pop(0): O(n) per pop. Usecollections.deque.
Interview questions 3
Answer out loud first, then reveal.
How do you choose between BFS, Dijkstra and Bellman-Ford?Show answer
By the weights. All edges equal: BFS, O(V + E), because hop count is the distance. Non-negative weights: Dijkstra with a min-heap, O((V + E) log V). Any negative edge: Bellman-Ford, O(V·E), which also detects negative cycles. Two shortcuts I check first: only 0/1 weights → 0-1 BFS with a deque; a DAG → relax in topological order, linear time, negatives allowed.
Why does Dijkstra break with negative edges?Show answer
Its proof says the closest unsettled node is final: any other route passes through a node that is already at least as far, and non-negative edges only add. A negative edge breaks that. A→C = 2, A→B = 5, B→C = −4: C is settled at 2, but A→B→C costs 1. The lazy-heap version can re-push C, but then it loses its O((V + E) log V) bound. With negatives, I use Bellman-Ford.
Cheapest flight with at most k stops: what changes?Show answer
The hop limit breaks plain Dijkstra: a cheap path with too many stops can block a pricier valid one, because dist is kept per node only. I run Bellman-Ford for exactly k + 1 rounds, relaxing from a copy of the previous round's distances so each round adds at most one edge: O(k·E). The alternative is Dijkstra over (node, stops) states.