Skip to content

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.

20 min read0/4 questions

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 costsAlgorithmTime
All equal (count steps)BFS with a queueO(V + E)
Only 0 or 10-1 BFS with a dequeO(V + E)
Any non-negative numberDijkstra with a min-heapO((V + E) log V)
Some negative, or "at most k edges"Bellman-FordO(V · E), or O(k · E)
All pairs, small V (a few hundred)Floyd-WarshallO(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.

Python
from collections import deque def oranges_rotting(grid): rows, cols = len(grid), len(grid[0]) queue = deque() fresh = 0 for r in range(rows): for c in range(cols): if grid[r][c] == 2: queue.append((r, c, 0)) # every source at minute 0 elif grid[r][c] == 1: fresh += 1 minutes = 0 while queue: r, c, t = queue.popleft() minutes = t for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1: grid[nr][nc] = 2 # mark when pushed, not when popped fresh -= 1 queue.append((nr, nc, t + 1)) return minutes if fresh == 0 else -1 assert oranges_rotting([[2, 1, 1], [1, 1, 0], [0, 1, 1]]) == 4assert oranges_rotting([[2, 1, 1], [0, 1, 1], [1, 0, 1]]) == -1assert oranges_rotting([[0, 2]]) == 0assert oranges_rotting([[2, 1, 1, 1, 2]]) == 2 # two waves meet in the middleprint(oranges_rotting([[2, 1, 1], [1, 1, 0], [0, 1, 1]]))
Output
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: hot belongs to *ot, h*t and ho*. Two words are neighbours exactly when they share a bucket.
  • Shortest Path in a Grid with Obstacles Elimination: you may walk through up to k walls. 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) where keys is a bitmask of the keys collected so far. With 6 keys there are 64 masks, so the state space is rows · 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.

Python
from collections import deque def open_lock(deadends, target): dead = set(deadends) if "0000" in dead: return -1 seen = {"0000"} queue = deque([("0000", 0)]) while queue: state, moves = queue.popleft() if state == target: return moves for i in range(4): d = int(state[i]) for nd in ((d + 1) % 10, (d - 1) % 10): nxt = state[:i] + str(nd) + state[i + 1:] if nxt not in seen and nxt not in dead: seen.add(nxt) queue.append((nxt, moves + 1)) return -1 def shortest_path_with_removals(grid, k): rows, cols = len(grid), len(grid[0]) if k >= rows + cols - 2: return rows + cols - 2 # enough to walk straight through start = (0, 0, k) seen = {start} queue = deque([(0, 0, k, 0)]) while queue: r, c, left, steps = queue.popleft() if (r, c) == (rows - 1, cols - 1): return steps for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: nleft = left - grid[nr][nc] # a wall costs one removal state = (nr, nc, nleft) if nleft >= 0 and state not in seen: seen.add(state) queue.append((nr, nc, nleft, steps + 1)) return -1 assert open_lock(["0201", "0101", "0102", "1212", "2002"], "0202") == 6assert open_lock(["8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"], "8888") == -1assert open_lock(["0000"], "8888") == -1assert open_lock([], "0009") == 1 # wheels wrap from 0 to 9 grid = [[0, 0, 0], [1, 1, 0], [0, 0, 0], [0, 1, 1], [0, 0, 0]]assert shortest_path_with_removals(grid, 1) == 6assert shortest_path_with_removals([[0, 1, 1], [1, 1, 1], [1, 0, 0]], 1) == -1assert shortest_path_with_removals([[0]], 0) == 0print(open_lock(["0201", "0101", "0102", "1212", "2002"], "0202"), shortest_path_with_removals(grid, 1))
Output
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.

0-1 BFS: obstacles removed to reach each cell
0##
##.
##.

# is an obstacle, . is empty, numbers are best known costs. Start at (0,0) with cost 0. Deque: [(0,0)].

1/6
Python
from collections import deque def minimum_obstacles(grid): rows, cols = len(grid), len(grid[0]) INF = float("inf") dist = [[INF] * cols for _ in range(rows)] dist[0][0] = 0 dq = deque([(0, 0)]) while dq: r, c = dq.popleft() if (r, c) == (rows - 1, cols - 1): return dist[r][c] for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: w = grid[nr][nc] # 0 = free, 1 = obstacle if dist[r][c] + w < dist[nr][nc]: dist[nr][nc] = dist[r][c] + w if w == 0: dq.appendleft((nr, nc)) else: dq.append((nr, nc)) return dist[rows - 1][cols - 1] assert minimum_obstacles([[0, 1, 1], [1, 1, 0], [1, 1, 0]]) == 2assert minimum_obstacles([[0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0]]) == 0assert minimum_obstacles([[0]]) == 0print(minimum_obstacles([[0, 1, 1], [1, 1, 0], [1, 1, 0]]))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
In 0-1 BFS, what goes wrong if you push 0-cost neighbours on the back of the deque instead of the front?
Need a nudge? A hint rules out a wrong answer.

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.

Dijkstra from A with lazy deletion
A0BCDE412153

currentwaitingdone

Heap: (0, A). Pop A at 0. Its distance is final.

1/7
Python
import heapq def dijkstra(graph, source, target=None): dist = {source: 0} prev = {} heap = [(0, source)] while heap: d, u = heapq.heappop(heap) if d > dist[u]: continue # stale entry if u == target: break # final once popped for v, w in graph.get(u, []): nd = d + w if nd < dist.get(v, float("inf")): dist[v] = nd prev[v] = u heapq.heappush(heap, (nd, v)) return dist, prev def path_to(prev, source, target): path = [target] while path[-1] != source: path.append(prev[path[-1]]) return path[::-1] def undirected(edges): g = {} for a, b, w in edges: g.setdefault(a, []).append((b, w)) g.setdefault(b, []).append((a, w)) return g g = undirected([("A", "B", 4), ("A", "C", 1), ("C", "B", 2), ("B", "D", 1), ("C", "D", 5), ("D", "E", 3)])dist, prev = dijkstra(g, "A")assert dist == {"A": 0, "B": 3, "C": 1, "D": 4, "E": 7}assert path_to(prev, "A", "E") == ["A", "C", "B", "D", "E"] neg = {"A": [("B", 2), ("C", 3)], "C": [("B", -2)]}wrong, _ = dijkstra(neg, "A", target="B")assert wrong["B"] == 2 # true answer is 1: Dijkstra is wrong hereprint(dist["E"], path_to(prev, "A", "E"), "negative-edge result:", wrong["B"])
Output
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:

ApproachIdeaTime on an R × C grid
Dijkstra on the maxPop the cell with the smallest worst-step so farO(RC log RC)
Binary search + BFSGuess an effort limit, check reachability with BFS using only edges within itO(RC log H), H = height range
Union-findSort all edges by cost, union them in order until start and end are connectedO(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.

Python
import heapqimport randomfrom collections import deque DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def min_effort_dijkstra(h): rows, cols = len(h), len(h[0]) best = [[float("inf")] * cols for _ in range(rows)] best[0][0] = 0 heap = [(0, 0, 0)] while heap: e, r, c = heapq.heappop(heap) if e > best[r][c]: continue if (r, c) == (rows - 1, cols - 1): return e for dr, dc in DIRS: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols: ne = max(e, abs(h[nr][nc] - h[r][c])) # max, not sum if ne < best[nr][nc]: best[nr][nc] = ne heapq.heappush(heap, (ne, nr, nc)) def min_effort_binary_search(h): rows, cols = len(h), len(h[0]) def can_cross(limit): seen = {(0, 0)} queue = deque([(0, 0)]) while queue: r, c = queue.popleft() if (r, c) == (rows - 1, cols - 1): return True for dr, dc in DIRS: nr, nc = r + dr, c + dc if (0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in seen and abs(h[nr][nc] - h[r][c]) <= limit): seen.add((nr, nc)) queue.append((nr, nc)) return False lo, hi = 0, max(map(max, h)) - min(map(min, h)) while lo < hi: mid = (lo + hi) // 2 if can_cross(mid): hi = mid else: lo = mid + 1 return lo assert min_effort_dijkstra([[1, 2, 2], [3, 8, 2], [5, 3, 5]]) == 2assert min_effort_dijkstra([[1, 2, 3], [3, 8, 4], [5, 3, 5]]) == 1assert min_effort_dijkstra([[1, 10, 6, 7, 9, 10, 4, 9]]) == 9random.seed(7)for _ in range(100): R, C = random.randint(1, 6), random.randint(1, 6) h = [[random.randint(1, 20) for _ in range(C)] for _ in range(R)] assert min_effort_dijkstra(h) == min_effort_binary_search(h)print(min_effort_dijkstra([[1, 2, 2], [3, 8, 2], [5, 3, 5]]))
Output
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.

Cheapest flights from 0 to 3 with at most 1 stop
0
0
inf
1
inf
2
inf
3
round = 0flights = 0..3: 0-1 100, 1-2 100, 2-0 100, 1-3 600, 2-3 200

Index = city, value = cheapest cost so far. k = 1 stop means at most 2 flights, so we run 2 rounds.

1/5
Python
def cheapest_flight(n, flights, src, dst, k): INF = float("inf") cost = [INF] * n cost[src] = 0 for _ in range(k + 1): # at most k + 1 flights nxt = cost[:] # read old, write new for a, b, price in flights: if cost[a] + price < nxt[b]: nxt[b] = cost[a] + price cost = nxt return -1 if cost[dst] == INF else cost[dst] def bellman_ford(n, edges, src): INF = float("inf") dist = [INF] * n dist[src] = 0 for _ in range(n - 1): changed = False for a, b, w in edges: if dist[a] + w < dist[b]: # in place is fine here dist[b] = dist[a] + w changed = True if not changed: break # early stop: nothing moved for a, b, w in edges: if dist[a] + w < dist[b]: return None # negative cycle reachable return dist flights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]]assert cheapest_flight(4, flights, 0, 3, 1) == 700assert cheapest_flight(4, flights, 0, 3, 2) == 400assert cheapest_flight(3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 1) == 200assert cheapest_flight(3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 0) == 500assert cheapest_flight(3, [[0, 1, 100]], 0, 2, 5) == -1 assert bellman_ford(3, [(0, 1, 2), (0, 2, 3), (2, 1, -2)], 0) == [0, 1, 3]assert bellman_ford(3, [(0, 1, 1), (1, 2, -1), (2, 1, -1)], 0) is Noneprint(cheapest_flight(4, flights, 0, 3, 1), bellman_ford(3, [(0, 1, 2), (0, 2, 3), (2, 1, -2)], 0))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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])
Need a nudge? Hints walk you through it.

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 the pairs0/5 matched

Match each problem to the algorithm that fits.

Choose an item, then its match on the other side.
Quick check
Why does Dijkstra treat a node's distance as final the moment it is popped from the heap?
Need a nudge? A hint rules out a wrong answer.
Key terms
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 u gives v a 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³).