Lesson 22 of 40Graphs in depth
Shortest Paths: BFS, 0-1 BFS, Dijkstra, Bellman-Ford
Pick the right shortest-path algorithm from the edge weights, then run multi-source BFS, BFS over states, 0-1 BFS, Dijkstra and Bellman-Ford correctly.
A delivery app needs the fastest route between a depot and a customer. A game needs the fewest moves for a character to reach a door it can only open after collecting a key. A flight search needs the cheapest itinerary with at most one stop. All three are shortest-path problems, but each one needs a different algorithm, and picking the wrong one either gives wrong answers or runs far too slowly. Graphs showed BFS for unweighted graphs and Dijkstra in one idea. This lesson is about choosing between the whole family, modelling the problem so the right algorithm applies, and avoiding the specific bugs interviewers look for.
Choose by the weights, not by the problem name
The single most useful question is: what can an edge cost? The answer picks the algorithm.
| Edge costs | Algorithm | Time |
|---|---|---|
| All equal (count steps) | BFS with a queue | O(V + E) |
| Only 0 or 1 | 0-1 BFS with a deque | O(V + E) |
| Any non-negative number | Dijkstra with a min-heap | O((V + E) log V) |
| Some negative, or "at most k edges" | Bellman-Ford | O(V · E), or O(k · E) |
| All pairs, small V (a few hundred) | Floyd-Warshall | O(V³) |
Each row is a special case of the one below it, and each is faster. Using Dijkstra on an unweighted grid works but wastes a log factor. Using BFS on weighted edges is simply wrong. Using Dijkstra with negative edges is wrong in a way that passes small tests, which is worse.
You may also hear about A*: Dijkstra plus a heuristic estimate of the remaining distance (such as straight-line distance on a map) that steers the search toward the target. If the estimate never overestimates, A* still finds the shortest path, often after exploring far fewer nodes. It matters in games and mapping; in interviews it is usually enough to know what it is.
Multi-source BFS
In Rotting Oranges, every rotten orange spreads rot to its four neighbours each minute. How long until all oranges rot? Running a BFS from each rotten orange separately would be slow and would double-count. Instead, put every source in the queue at distance 0 before you start. BFS then grows all the rings at once, and the first time any wave reaches a cell is its true distance to the nearest source.
Think of it as one BFS from an imaginary super-source connected to every real source by a free edge. The same trick solves Walls and Gates (distance from each room to the nearest gate) and 01 Matrix (distance from each cell to the nearest 0): seed all the targets, then search outward once. It is O(rows · cols) no matter how many sources there are.
Press Run (⌘ Enter) to see what happens.BFS over states, not cells
BFS finds the fewest moves between states. Often a state is more than a position, and the trick is to put exactly what matters for the future into it.
- Open the Lock: a state is a 4-digit string. Each state has 8 neighbours (turn one of 4 wheels up or down). Dead ends are states you may never enter.
- Word Ladder: a state is a word, and neighbours differ by one letter. Comparing every pair of words is O(N² · L). Instead, bucket words by wildcard patterns:
hotbelongs to*ot,h*tandho*. Two words are neighbours exactly when they share a bucket. - Shortest Path in a Grid with Obstacles Elimination: you may walk through up to
kwalls. Position alone is not enough, because reaching a cell with 2 removals left is better than reaching it with 0 left. The state is(r, c, remaining). - Shortest Path to Get All Keys: the state is
(r, c, keys)wherekeysis a bitmask of the keys collected so far. With 6 keys there are 64 masks, so the state space isrows · cols · 64.
The cost of BFS is the number of states times the moves per state, so always estimate it before coding. For Word Ladder, a known speed-up is bidirectional BFS: search from both ends and stop when the two frontiers meet. Each side only has to go half as deep, and because the frontier grows exponentially with depth, that can cut the work dramatically.
Press Run (⌘ Enter) to see what happens.0-1 BFS: when some moves are free
In Minimum Obstacle Removal to Reach Corner, moving into an empty cell costs 0 and moving into an obstacle costs 1 (you remove it). Plain BFS is wrong, because it treats every move as one step. Dijkstra is correct but uses a heap for a problem that has only two edge weights.
0-1 BFS replaces the queue with a deque. When you relax an edge of cost 0, push the neighbour on the front (appendleft), because it is just as close as the node you are expanding. When the edge costs 1, push it on the back. The deque then always holds at most two distance values, d at the front and d + 1 behind, in sorted order, which is exactly what Dijkstra's heap would give you, at O(1) per push. A node can be pushed twice (first with a worse distance), so keep a dist array and only push when the distance improves.
# is an obstacle, . is empty, numbers are best known costs. Start at (0,0) with cost 0. Deque: [(0,0)].
Press Run (⌘ Enter) to see what happens.Dijkstra done right
Graphs gave you the core loop. Four details turn it into the version you should write in an interview.
Lazy deletion. Python's heapq cannot lower a key that is already in the heap. Instead, push a new entry whenever a distance improves and leave the old one in place. When you pop an entry whose distance is larger than the best known (d > dist[u]), it is stale: skip it. The heap may hold up to E entries, which keeps the cost at O(E log E), and since E is at most V², log E is at most 2 log V, so this is still O((V + E) log V).
Early exit. If you only need one target, return as soon as the target is popped. Not when it is first pushed: a later, cheaper path may still be found before it reaches the top of the heap.
Path reconstruction. Keep a prev map. Every time you improve dist[v] through u, set prev[v] = u. At the end, walk back from the target to the source and reverse.
Negative edges break it. Dijkstra assumes that when a node is popped, nothing later can make it cheaper, because every remaining path starts at least as far away and edges only add cost. A negative edge breaks that assumption. Take edges A → B costing 2, A → C costing 3 and C → B costing -2. Dijkstra pops B at cost 2 and stops early if B is the target, but the true cost is 3 - 2 = 1. Without early exit, the lazy version may repair this by re-pushing B, but then a node can be popped many times and the running time is no longer bounded by O((V + E) log V). With negative edges, use Bellman-Ford.
Heap: (0, A). Pop A at 0. Its distance is final.
Press Run (⌘ Enter) to see what happens.Practice the plain version with the network-delay-time problem: run Dijkstra from the source and return the largest distance, or -1 if any node is unreachable.
Bottleneck paths: Path With Minimum Effort
In Path With Minimum Effort, a route's cost is not the sum of its steps but the largest height difference along it. Dijkstra still works, because the cost never decreases as a path gets longer: replace d + w with max(d, w). Swim in Rising Water is the same idea with cell heights instead of differences.
There are three valid approaches, and comparing them is a common follow-up:
| Approach | Idea | Time on an R × C grid |
|---|---|---|
| Dijkstra on the max | Pop the cell with the smallest worst-step so far | O(RC log RC) |
| Binary search + BFS | Guess an effort limit, check reachability with BFS using only edges within it | O(RC log H), H = height range |
| Union-find | Sort all edges by cost, union them in order until start and end are connected | O(RC log RC) for the sort |
Binary search works because the question "can I get across with effort at most x?" is monotonic: if yes for x, then yes for anything larger. The union-find version is Kruskal's idea from Union-Find in Depth: the answer is the weight of the edge that first connects the two corners.
Press Run (⌘ Enter) to see what happens.Bellman-Ford and "at most k stops"
Bellman-Ford relaxes every edge, over and over. After round i, every node has its best cost among paths that use at most i edges. A shortest path without a cycle has at most V - 1 edges, so V - 1 rounds are enough even with negative edges. If a V-th round still improves something, there is a negative cycle reachable from the source, and "shortest" has no meaning.
That "round i means at most i edges" property is why it solves Cheapest Flights Within K Stops: k stops means at most k + 1 flights, so run exactly k + 1 rounds. Dijkstra cannot do this directly, because it throws away a more expensive path that used fewer flights, and that path may be the only one that fits the limit.
The classic bug is updating the distance array in place during a round. Then an edge relaxed later in the same round can build on a value that was set earlier in that round, so one round can extend a path by several edges. For the unbounded algorithm that is harmless (it only converges faster). For "at most k edges" it is wrong: it lets paths use more flights than allowed. Each round must read from a copy of the previous round.
Index = city, value = cheapest cost so far. k = 1 stop means at most 2 flights, so we run 2 rounds.
Press Run (⌘ Enter) to see what happens.What does this print?
flights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]]
k = 1
cost = [0, float("inf"), float("inf"), float("inf")]
for _ in range(k + 1):
for a, b, price in flights: # no copy: updates in place
if cost[a] + price < cost[b]:
cost[b] = cost[a] + price
print(cost[3])Floyd-Warshall for all pairs
When you need the distance between every pair of nodes and V is small (a few hundred), Floyd-Warshall is the shortest code you can write: three nested loops, with the middle node m on the outside.
for m in range(n):
for i in range(n):
for j in range(n):
if dist[i][m] + dist[m][j] < dist[i][j]:
dist[i][j] = dist[i][m] + dist[m][j]After the outer loop has handled nodes 0..m, dist[i][j] is the best path that only passes through those nodes in between. That is why m must be the outermost loop; putting it inside is a common bug that gives wrong answers. It handles negative edges, and a negative value on the diagonal (dist[i][i] < 0) reveals a negative cycle. It is O(V³) time and O(V²) space, so at V = 1,000 it is already a billion steps. For all pairs on a large sparse graph with non-negative weights, running Dijkstra from each node is usually faster.
Match each problem to the algorithm that fits.
- multi-source BFS
- BFS that starts with every source in the queue at distance 0, giving each node its distance to the nearest source.
- state space
- All combinations of what matters for the future, such as position plus keys held. BFS runs over states, not just cells.
- 0-1 BFS
- Shortest paths with edge weights 0 or 1, using a deque: 0-cost moves go on the front, 1-cost moves on the back. O(V + E).
- lazy deletion
- In Dijkstra, pushing a new heap entry on each improvement and skipping popped entries whose distance is out of date.
- relaxation
- Checking whether going through
ugivesva shorter distance, and updating it if so. - Bellman-Ford
- Relax every edge V - 1 times. Handles negative edges, detects negative cycles, and round i gives best costs with at most i edges.
- Floyd-Warshall
- All-pairs shortest paths with three nested loops and the middle node outermost. O(V³).