Breadth-first search
The conceptHow a maze solver finds the shortest route without trying every path
Breadth-first search (BFS) explores a graph, meaning dots (nodes) joined by lines (edges), ring by ring. It visits everything one step from the start, then everything two steps away, then three, and so on.
Take a small friend network: You know Bea and Cal. Bea knows Dan and Eve, Cal knows Eve and Fay, and Dan knows Gus. BFS visits You (ring 0), then Bea and Cal (ring 1), then Dan, Eve and Fay (ring 2), then Gus (ring 3).
Because rings grow outward, BFS first reaches each node by a shortest route, counted in edges. In a maze, squares are nodes and open moves are edges, so the ring where BFS meets the exit is the fewest moves.
What it’s forGives each node its distance from the start, in edges, at the moment BFS first finds it.
dist(v) = dist(u) + 1
- v
- a node seen for the first time
- u
- the node BFS was expanding when it found v
- dist
- number of edges from the start; dist(start) = 0
What it givesThe fewest-hops distance from the start to every reachable node.
- dist(You) = 0
- Bea found from You: 0 + 1 = 1; Dan found from Bea: 1 + 1 = 2
- Gus found from Dan: 2 + 1 = 3