Breadth-first search
Breadth-first search keeps a queue of nodes it has reached but not yet looked at. It takes the oldest one, looks at each of that node’s neighbours, and adds any it has never seen to the back of the queue. Because the queue is first in, first out, every node at distance one is dealt with before any node at distance two, which is why the first arrival at a node is always by a fewest-edges path.
Its frontier
A queue, taken from the front.
When it is the right choice
It is the right choice whenever "fewest steps" is the question and every step costs the same: a maze, a friend-of-a-friend search, the number of moves to solve a puzzle. It is also the cheapest way to find out whether two nodes are connected at all. What it cannot do is take weights into account — on a weighted graph it finds the path with the fewest edges, which is often not the cheapest one, and that is Dijkstra’s job rather than a flaw in this.
How it works
- Put the starting node in the queue with a distance of zero.
- Take the node at the front of the queue.
- Look at each of its neighbours in turn.
- A neighbour never seen before gets a distance one greater, remembers where it came from, and joins the back of the queue.
- A neighbour already seen is left alone: it was reached by a path at least as short.
- Stop when the queue is empty, or earlier once the target has been taken from it.
Worth noticing
- The queue is the whole algorithm. Watch the track beneath the graph rather than the colours: depth-first search is this page with the queue replaced by a stack, and nothing else on the screen changes.
- A node is given its distance when it is *added* to the queue, not when it is taken out. That is safe here and it is not safe in Dijkstra, which is the difference between the two pages.
- The peak-frontier counter is the honest cost of this algorithm. On a wide graph the queue holds a whole level at once, which is why breadth-first search can use far more memory than depth-first search on the same graph.
Cost
- Best
- O(V + E)
- Average
- O(V + E)
- Worst
- O(V + E)
- Extra space
- O(V)
- Runs on
- a grid with walls; a weighted undirected graph; a directed acyclic graph; a directed graph with a cycle
- Largest grid
- 11 by 7 cells
- Largest graph
- 14 nodes, 28 edges
The limits are pedagogical rather than technical: this tool keeps a cost and a predecessor for every node in every recorded step, so the size of the graph sets the size of the trace directly, and a run has to stay short enough to sit and watch. A graph that would take more than three thousand steps on this algorithm is refused before a single step is generated, from a formula in the number of nodes and edges rather than by running it and finding out.
Graphs are generated from a seed, so the link in your address bar draws exactly the graph on your screen — no part of it is random in a way a reload could change.