Breadth-first search
A queue, level by level — and the shortest path in an unweighted graph.
Before you start
Breadth-first search explores a graph in rings. First every node one step from the start, then every node two steps away, then three — never moving outward until the current ring is completely finished.
The mechanism is a **queue**. Take a node off the front, look at its neighbours, put any unseen ones on the back. Because a queue is first-in-first-out, everything at distance 1 is already waiting ahead of anything at distance 2.
That ordering gives BFS its most useful property for free: in an unweighted graph, **the first time you reach a node is always by a shortest path**. It is the algorithm behind "fewest moves to solve this puzzle" and "degrees of separation".
Graph
edges are undirected; BFS explores by distanceQueue (FIFO)
oldest node leaves firstA is queued and marked visited. Distance 0.
Step 1 of 8. Enqueue the start node. The search begins at **A**. It goes into the queue and is marked visited immediately. Marking on *enqueue* rather than on dequeue matters — it is what stops a node being added to the queue twice when two different neighbours both discover it.
Step 01 / 08
Enqueue the start node
The search begins at **A**. It goes into the queue and is marked visited immediately.
Marking on *enqueue* rather than on dequeue matters — it is what stops a node being added to the queue twice when two different neighbours both discover it.
void bfs(Graph *g, int start) { bool visited[N] = { false }; Queue q; enqueue(&q, start); visited[start] = true; while (!empty(&q)) { int node = dequeue(&q); /* FIFO: oldest first */ visit(node); for (int nb : neighbours(g, node)) { if (!visited[nb]) { visited[nb] = true; /* mark on ENQUEUE */ enqueue(&q, nb); /* not on dequeue */ } } }}