A Breadth-First Search
13 — Algorithms
Explore in rings — find shortest paths

Breadth-First Search

Spread out one ring at a time from a starting point. A queue does the bookkeeping, and the level each vertex lands on is its shortest distance from the source.

Breadth-first search explores a graph in expanding rings. Starting from a source vertex, it visits all neighbors at distance 1, then everything at distance 2, and so on — never going deep until a whole level is done. The engine is a queue: you enqueue the source, then repeatedly dequeue the front vertex and enqueue any neighbors you haven't seen. Because the queue is first-in, first-out, vertices come out in exact order of distance. That gives BFS a superpower: the level where a vertex is first found is its shortest distance (in edges) from the source. Every vertex and edge is touched once — O(V + E).

Try it in 3D

Run BFS and watch the wave spread outward. Each vertex is colored and labelled by its distance from the source; the strip below shows the live queue. Drag to orbit.

Drag to rotate — scroll to zoom
queue ?empty
speed
Press —Run BFS— to watch the wave spread.ready
Source — level 0 Level 1 Level 2 Level 3 Shortest path

Why it works

The queue is not a detail — it is the whole reason BFS discovers vertices in distance order.

Cost cheat sheet

Linear in the size of the graph, with a queue and a visited set as the only memory cost.