Loading...
Breadth-First Search is a fundamental graph traversal that explores all vertices in order of their distance (in edges) from a starting source. It is the backbone for many unweighted shortest path, connectivity, and level-structure algorithms.
Given a graph G = (V, E) and a source vertex s, BFS systematically explores the edges of G to discover every vertex reachable from s. It computes the shortest path distance (in number of edges) from s to every discovered vertex and records a breadth-first tree (parent pointers) that captures shortest paths.
Each vertex enqueued at most once; each edge considered at most twice (undirected) or once (directed).
1BFS(G, s):2 for each vertex v in G:3 color[v] ← WHITE4 dist[v] ← ∞5 parent[v] ← NIL6 color[s] ← GRAY7 dist[s] ← 08 enqueue(Q, s)9 while Q not empty:10 u ← dequeue(Q)11 for each neighbor v of u:12 if color[v] = WHITE:13 color[v] ← GRAY14 dist[v] ← dist[u] + 115 parent[v] ← u16 enqueue(Q, v)17 color[u] ← BLACK
Practice BFS interactively to see queue evolution, frontier layers, and path reconstruction.
Go to Simulation