Module A-5·14 min read

Breadth-first traversal, queue-based level exploration, and shortest-path-in-hops problems.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module A-5 — Graph Traversal: Breadth-First Search (BFS)

What this module covers: Module A-4's DFS goes deep before it goes wide — following one path as far as it can before backtracking. BFS does the opposite: it explores layer by layer, using Module F-7's queue instead of Module F-6's stack. This module covers why that single structural swap gives BFS a property DFS can't offer — a guarantee of shortest path, measured in edge count, on an unweighted graph.


Layer by Layer, Using a Queue

BFS explores every neighbor of the starting node before moving on to their neighbors — exactly Module P-4's level-order traversal, generalized from a tree to a general graph, with the same visited-set addition Module A-4 introduced for handling cycles:

typescript

Compare the visited handling here directly to Module A-4's iterative DFS: DFS marked a node visited when it was popped (allowing the same node to sit in the stack multiple times simultaneously, discarded later when redundant), while BFS marks a node visited when it's enqueued — the moment it's first discovered, before it's even been processed. This isn't a stylistic choice; it's what guarantees BFS's core property, covered next.


Why BFS Guarantees Shortest Path (in Hops)

Because BFS processes nodes in strict FIFO order (Module F-7), and marks a node visited the instant it's first discovered, the first time any node is reached, it's guaranteed to have been reached via a shortest possible path from the start, measured in number of edges. Every node at distance 1 from the start gets enqueued before any node at distance 2 can be discovered (since distance-2 nodes are only reachable through a distance-1 node being processed first) — this is the exact same "every depth-d node is dequeued before any depth-(d+1) node" guarantee Module P-4 established for level-order tree traversal, now holding for a general graph.

typescript

DFS cannot offer this guarantee — it might stumble onto the target via a long, winding path long before it happens to try the short, direct one, since DFS commits to going deep along whichever neighbor it tries first, with no structural preference for "closer" nodes. This is the single most important reason to choose BFS over DFS: DFS answers "can I reach this node, and here's one way"; BFS answers "what's the fewest hops to reach this node."


Application: Shortest Path in a Grid

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.