Breadth-first search (BFS) visits the vertices reachable from a start vertex in nondecreasing order of their distance from , where the distance of a vertex is the number of edges on a shortest path from to it. Every vertex at distance is visited before any vertex at distance .
Its applications, among them shortest paths in unweighted graphs, connected components and bipartiteness testing, follow from this level-by-level visit order.
Core idea
BFS explores vertices in order of the length of their shortest path from the starting vertex. In an unweighted graph, the shortest path between two vertices can therefore be found with BFS.
Weights break the guarantee
BFS orders vertices by edge count, not by path weight. On a weighted graph the first path BFS finds can carry more total weight than a path with more edges, so weighted shortest paths are computed with Dijkstra’s algorithm instead.
Intuition
BFS runs on a queue. The start vertex is enqueued first, and when a vertex is dequeued, its undiscovered neighbors are enqueued. Every vertex at distance enters the queue before any vertex at distance , and so on, so the traversal processes the graph one distance class at a time. A vertex is therefore first discovered along a shortest path from the start vertex.
Level sets
The traversal can be described by level sets of vertices. Let be the start vertex and define
Each level is exactly the set of vertices at distance from . The proof is by induction on . Suppose every vertex in levels through lies at distance equal to its level index. A vertex has a neighbor in , so its distance is at most . Its distance is also not smaller than , because a vertex at distance has a neighbor at distance , which by hypothesis lies in and would place in .
In the graph below, the levels are the distance classes around . The edge between and joins two vertices of , which is the condition a bipartiteness check detects.
flowchart LR subgraph L0 s((s)) end subgraph L1 a((a)) b((b)) end subgraph L2 c((c)) d((d)) end s --- a s --- b a --- b a --- c b --- c b --- d
What it solves
- Shortest paths in unweighted graphs.
- Connected components, by running BFS from every unvisited vertex.
- Bipartiteness checks, since an edge between two vertices in the same level implies an odd cycle.