LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How do you get the actual fewest-edge path from u to z out of a BFS, and how do you notice that there is none?

Run BFS from u and record for each newly visited vertex w the vertex it was discovered from, its parent. Afterwards walk from z along the parent links back to u and reverse the list. If z was never visited, it lies in another connected component and no path exists.

from collections import deque

def shortest_path(graph, u, z):
    parent = {u: None}
    queue = deque([u])
    while queue:
        v = queue.popleft()
        if v == z:
            break                              # z's path is complete
        for e in graph.incident_edges(v):
            w = graph.opposite(v, e)
            if w not in parent:                # not visited yet
                parent[w] = v
                queue.append(w)
    if z not in parent:
        return None                            # z is unreachable from u
    path = []
    while z is not None:
        path.append(z)
        z = parent[z]
    return path[::-1]

The parent links are the discovery edges stored backwards: together they form the BFS tree, and the path along them is a shortest one, because the tree path to every vertex of $L_i$ has exactly i edges. The walk back from z takes only as many steps as the path is long.

The search can stop as soon as z comes out of the queue, since its parent is fixed and everything after it is at least as far from u. One BFS run answers the related questions as well: whether a path exists at all (was z visited?) and how many edges the shortest path has (the level of z).

Go deeper:

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 27, 2026