Breadth-First Search
You're standing in city A with a map of roads. You want to find the shortest route to every other city. The strategy: first visit every city directly connected to A. Then visit every city connected to those cities. Then the next ring out. And so on.
This ring-by-ring expansion is Breadth-First Search (BFS). It explores all cities at distance 1 before any city at distance 2, all cities at distance 2 before distance 3, and so forth.
The Queue is the key
BFS needs a queue — a first-in, first-out waiting room. Cities waiting to be explored line up in order. The city at the front of the line gets explored next, and its unvisited neighbors join the back of the line.
Why BFS finds the shortest path
BFS visits cities in order of their distance from the start. The first time BFS reaches a city, it has taken the shortest possible route to get there — because it always finishes exploring shorter paths before longer ones.
This property only holds for unweighted graphs. If roads have different lengths (weights), use Dijkstra's algorithm instead.
Level-order traversal
BFS naturally produces a level-order traversal. Level 0 is just the start node. Level 1 is all direct neighbors. Level 2 is all neighbors of neighbors. You can track the level by noting when the current layer of the queue is exhausted before starting the next.
← → arrow keys to step · click elements to interact