ArticlesTrees and graphs

Trees and graphs

Breadth-first search

A queue walks neighbours, then neighbours of neighbours. On equal edge costs, the first time you arrive is the fewest edges.

Breadth-first search uses a queue. Start at the source, then visit neighbours, then neighbours of neighbours. The first time you reach the target, you got there in the fewest edges. That claim is only true when every edge has the same cost. Weighted edges need a different rule.

Level order on a tree is the same walk with a different story. Visit every node on one depth, then the next depth. The queue is what keeps this layer ahead of the next layer. The starter that builds a tree from a level-order list is doing that walk in reverse, reading the layer you would have visited.

Mark a vertex when you first enqueue it, not when you dequeue it, or the same neighbour gets queued many times. Carry the distance with the vertex, or store it at the moment you enqueue. If the target is never reached, there is no path. The distance from a vertex to itself is 0, before you have walked anywhere.