← Back to Algorithms, page 4

algorithms-0066 · Easy fresher

Breadth-first search for shortest paths in an unweighted graph: compute distances from a source and rebuild one shortest path to a target.

BFS explores nodes in rings of increasing distance using a FIFO queue. Mark a node when it is enqueued and set its distance to the parent's plus one; the first time a node is reached is via a shortest path. Storing a parent pointer per node lets the path be rebuilt by walking back from the target. Time O(V + E), space O(V).

Full answer

Problem

Given a directed or undirected unweighted graph and a source s, return the fewest-edge distance from s to every reachable node, and one shortest path from s to a target t.

Example: {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [], 5: [0]} from 0 gives distances {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}; one shortest path to 4 is [0, 1, 3, 4]; node 5 is unreachable from 0.

Constraints: up to 10^5 nodes and edges.

Brute force

DFS over all simple paths and keep the shortest: exponential in the worst case. Repeated relaxation of all edges (Bellman-Ford with unit weights) is polynomial but O(V * E).

Optimal approach

  1. dist = {s: 0}, queue [s].
  2. Pop u from the front. For each neighbour v not in dist, set dist[v] = dist[u] + 1, parent[v] = u, and enqueue v.
  3. To rebuild the path to t, follow parent from t back to s and reverse.

Why it works

The queue always contains nodes at distance d followed by nodes at distance d + 1, never further. So nodes are dequeued in non-decreasing distance order, and the first time a node is discovered, it is from a node one step closer to s than any other discoverer could be. Marking on enqueue (not on dequeue) prevents a node from being queued twice with a worse distance.

Complexity

O(V + E) time, O(V) space for the queue, distances and parents.

Code

python
import random
from collections import deque


def bfs_distances(adj, start):
    """Fewest edges from start to every reachable node. O(V + E)."""
    dist = {start: 0}
    q = deque([start])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in dist:            # mark when enqueued, not when dequeued
                dist[v] = dist[u] + 1
                q.append(v)
    return dist


def shortest_path(adj, start, goal):
    """Return one shortest path as a list of nodes, or [] if unreachable."""
    parent = {start: None}
    q = deque([start])
    while q:
        u = q.popleft()
        if u == goal:
            path = []
            while u is not None:
                path.append(u)
                u = parent[u]
            return path[::-1]
        for v in adj[u]:
            if v not in parent:
                parent[v] = u
                q.append(v)
    return []


def brute_dist(n, adj, s):
    """Bellman-Ford style relaxation with unit weights: O(V * E)."""
    INF = float("inf")
    d = [INF] * n
    d[s] = 0
    for _ in range(n):
        for u in range(n):
            for v in adj[u]:
                d[v] = min(d[v], d[u] + 1)
    return {u: d[u] for u in range(n) if d[u] < INF}


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [], 5: [0]}
    assert bfs_distances(adj, 0) == {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
    assert shortest_path(adj, 0, 4) == [0, 1, 3, 4]
    assert shortest_path(adj, 0, 5) == []
    assert shortest_path(adj, 2, 2) == [2]
    rng = random.Random(66)
    for _ in range(500):
        n = rng.randint(1, 10)
        g = {u: [] for u in range(n)}
        for _ in range(rng.randint(0, 20)):
            g[rng.randrange(n)].append(rng.randrange(n))
        s = rng.randrange(n)
        d = bfs_distances(g, s)
        assert d == brute_dist(n, g, s)
        t = rng.randrange(n)
        p = shortest_path(g, s, t)
        assert (len(p) - 1 if p else None) == d.get(t)
    print("all tests passed")

Save as b66_bfs.py and run python3 b66_bfs.py. It prints all tests passed (Python 3.13.5).

Edge cases

Source equals target (path [s]). Unreachable target (return [] or -1). Directed edges that only go one way. Weighted graphs: BFS is wrong once weights differ; use 0-1 BFS for weights 0 and 1, Dijkstra for non-negative weights.

Pattern

Level-order exploration for unweighted shortest paths. It covers grid mazes, word ladder (implicit graph of one-letter changes), multi-source BFS (rotting oranges, distance to nearest exit), and state-space search where each move costs 1.

python
import random
from collections import deque


def bfs_distances(adj, start):
    """Fewest edges from start to every reachable node. O(V + E)."""
    dist = {start: 0}
    q = deque([start])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in dist:            # mark when enqueued, not when dequeued
                dist[v] = dist[u] + 1
                q.append(v)
    return dist


def shortest_path(adj, start, goal):
    """Return one shortest path as a list of nodes, or [] if unreachable."""
    parent = {start: None}
    q = deque([start])
    while q:
        u = q.popleft()
        if u == goal:
            path = []
            while u is not None:
                path.append(u)
                u = parent[u]
            return path[::-1]
        for v in adj[u]:
            if v not in parent:
                parent[v] = u
                q.append(v)
    return []


def brute_dist(n, adj, s):
    """Bellman-Ford style relaxation with unit weights: O(V * E)."""
    INF = float("inf")
    d = [INF] * n
    d[s] = 0
    for _ in range(n):
        for u in range(n):
            for v in adj[u]:
                d[v] = min(d[v], d[u] + 1)
    return {u: d[u] for u in range(n) if d[u] < INF}


if __name__ == "__main__":
    adj = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: [], 5: [0]}
    assert bfs_distances(adj, 0) == {0: 0, 1: 1, 2: 1, 3: 2, 4: 3}
    assert shortest_path(adj, 0, 4) == [0, 1, 3, 4]
    assert shortest_path(adj, 0, 5) == []
    assert shortest_path(adj, 2, 2) == [2]
    rng = random.Random(66)
    for _ in range(500):
        n = rng.randint(1, 10)
        g = {u: [] for u in range(n)}
        for _ in range(rng.randint(0, 20)):
            g[rng.randrange(n)].append(rng.randrange(n))
        s = rng.randrange(n)
        d = bfs_distances(g, s)
        assert d == brute_dist(n, g, s)
        t = rng.randrange(n)
        p = shortest_path(g, s, t)
        assert (len(p) - 1 if p else None) == d.get(t)
    print("all tests passed")

Distances and parent-pointer path reconstruction, checked against unit-weight relaxation on random directed graphs.

Complexity

Time: O(V + E). Space: O(V). Stopping as soon as the target is dequeued saves time but not the worst-case bound.

By level

Fresher: Writes BFS with a deque and a distance map, and traces it on a small graph. Rebuilds a path using parent pointers.

Mid: Explains the queue invariant that makes BFS correct and the effect of marking on enqueue. Applies BFS to grids and implicit graphs.

Senior: Discusses bidirectional BFS and its effect on explored nodes, BFS on graphs that do not fit in memory, and frontier-based parallel BFS. Chooses between BFS, 0-1 BFS and Dijkstra based on the weights.

Key points

  • FIFO queue gives non-decreasing distance order
  • Mark when enqueued
  • dist[v] = dist[u] + 1 on discovery
  • Parent pointers rebuild the path
  • Only valid for unweighted (or equal-weight) edges

Common mistakes

  • Marking visited on dequeue, causing duplicate enqueues
  • Using a list with pop(0)
  • Using BFS on weighted graphs
  • Forgetting the unreachable case

Follow-ups

  • How would you search from both ends (bidirectional BFS)?
  • How do you find shortest distances from several sources at once?
  • What changes when edges have weight 0 or 1?

Tips

  • State the queue invariant
  • Mention marking on enqueue
  • Explain when BFS stops being correct

Evaluation rubric

  • Correct BFS with distances
  • Path reconstruction
  • Correct complexity
  • Knows limits on weighted graphs