Breadth-First Search (BFS)
–
Pseudocode
1visited[s] ← true; queue ← [s]2while queue is not empty:3 u ← queue.dequeue(); visit(u)4 for each neighbour v of u:5 if not visited[v]:6 visited[v] ← true; parent[v] ← u; queue.enqueue(v)
Visited
0
Edges checked
0
vertex being processedqueuewaiting in the queuefinished / tree edge
What is Breadth-First Search?
Breadth-first search visits a graph in layers: first the start vertex, then all of its neighbours, then all of their unvisited neighbours, and so on. It is like a ripple spreading out from where a stone hit the water.
The trick is a queue: newly found vertices join at the back, and the next vertex to explore is taken from the front. That keeps vertices in order of their distance from the start, which is why BFS also finds the shortest path (fewest edges) in an unweighted graph. Look at the d = labels on the board.
Explore the nearest vertices first: one layer at a time.
Using the Visualizer
- • Edit graph slides out the adjacency matrix: click a cell to add or remove an edge, or use Random / Example. Tick Directed for one-way edges.
- • Pick the start from the menu or click a vertex.
- • On the right: the queue, the visit order, and each vertex's visited flag, parent and distance. Green edges are the BFS tree: following parents back gives a shortest path.
- • Neighbours are tried in increasing order, so the result matches the code below.
Implementation
Properties & Complexity
Time Complexity
- • Adjacency list: O(V + E)
- • Adjacency matrix: O(V²)
- • Every vertex is enqueued and dequeued at most once
Space & Properties
- • Space: O(V) for the queue and arrays
- • Shortest paths: yes, by edge count
- • Order: layer by layer
Where BFS Is Used
- • Shortest routes when every step costs the same
- • Social networks: friends, friends of friends…
- • Web crawlers and broadcasting in networks
- • Puzzles: fewest moves to solve a maze or a cube
Limitations
- • Weighted graphs: fewest edges isn't cheapest; use Dijkstra
- • Memory: a wide graph puts many vertices in the queue at once
- • Reachability: only finds vertices connected to the start