What Is BFS?#
Breadth-First Search (BFS) explores a graph level by level. It visits all neighbours of the starting node first, then all neighbours of those neighbours, and so on, expanding outward like ripples in a pond.
The key data structure is a queue (FIFO). DFS uses a stack (or recursion); BFS uses a queue.
How It Works#
- Add the start node to the queue and mark it visited
- While the queue is not empty:
- Dequeue a node
- Process it
- Enqueue all its unvisited neighbours, marking them visited
Notice the level-by-level structure: → →
Implementation#
- Time Complexity: O(V + E), since it visits every vertex and edge once
- Space Complexity: O(V), because the queue can hold up to O(V) nodes at once
Interactive Lab#
Let's take the example in this visualization: six vertices A to F joined by nine edges, with A marked as the source and E as the target. Press play and follow the queue. A is dequeued first and enqueues its neighbours B and D; B is dequeued next and adds C and E behind them. Every vertex one hop from A is coloured before any vertex two hops away. That is the entire guarantee BFS gives you, and it is why the path it reconstructs, A → B → E, is the shortest one by edge count.
BFS Finds the Shortest Path#
In an unweighted graph, BFS guarantees the shortest path (fewest edges) from the start to every reachable node. The first time BFS reaches a node is always via the shortest route.
Key Applications#
- Shortest path in unweighted graphs (social networks, maps)
- Web crawlers: explore pages level by level
- Network broadcasting: how packets propagate
- Level-order traversal of binary trees
- Multi-source BFS: flood fill (paint bucket tool), spreading fire
DFS vs BFS Summary#
| Property | DFS | BFS |
|---|---|---|
| Data structure | Stack / recursion | Queue |
| Memory (dense graphs) | Less | More |
| Finds shortest path | ✗ | ✓ (unweighted) |
| Good for | Topology, cycles, backtracking | Shortest path, levels |
What to Remember#
BFS is the right tool whenever you care about distance from the source. For shortest-path problems on unweighted graphs, BFS is optimal. The queue ensures nodes are processed in order of their distance from the start.