Codele / Algorithms
Breadth-first search
Drop a stone in a pond and ripples spread in rings. Breadth-first search explores a map the same way: every town one step away, then every town two steps away, and so on.
- A graph is towns (dots) joined by roads (lines). Breadth-first search (BFS) explores it in rings: all neighbours first, then their neighbours.
- It uses a queue: towns join at the back and are taken from the front, so nearer towns are always handled first.
- Keep a record of towns already seen, or the search would walk in circles forever.
- The first time BFS reaches a town is by a route with the fewest steps.
- BFS finds fewest steps, not shortest distance in kilometres: it counts roads, not their lengths.
Loading the playable lesson…