
Think together · Start with a little story
The girl draws circles on the ground: first check everywhere you can reach in one step, then everywhere you can reach in two.
Lay out the process
- Layer 0Starting point
- Layer 1Reachable in one step
- Layer 2First reachable in two steps
- QueueKeep items in order
Breadth-first search expands outward layer by layer.
Put the starting point in a queue. After removing a node, add its newly discovered neighbors. Marking them when enqueued usually prevents the same node from being queued repeatedly.
Watch how the queue changes
Start at A. The row shows the queue from front to back.
A has been discovered, and its distance is 0.
Enqueue and mark the undiscovered B and C. Their distance is 1.
D is enqueued at distance 2. C stays ahead of D in the queue.
E is enqueued at distance 2. The first layer has now been processed.
There are no new undiscovered neighbors. This example visits A, B, C, D, E.
01What is BFS?
BFS (Breadth-First Search) starts at a point and expands outward one layer at a time.
02Why is it like a ripple?
Drop a stone into water: ripples reach nearby places before farther ones.
BFS also handles states closer to the start before states farther away.
03Why does BFS use a queue?
A queue is first-in, first-out.
The node discovered first is handled first, which ensures that closer layers are expanded sooner.
04The basic code structure
std::queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : graph[u]) {
if (!visited[v]) {
visited[v] = true;
q.push(v);
}
}
}
05Why mark visited when enqueuing?
If you wait until a node is removed from the queue, multiple predecessors may add the same node more than once.
06What can BFS do?
- Traverse a tree level by level.
- Find the fewest steps in an unweighted graph.
- Find a shortest path through a maze.
- Search for connectivity.
- Solve multi-source expansion problems.
What have you learned?
- BFS expands outward layer by layer according to distance.
- BFS usually uses a queue.
- Nodes discovered first are processed first.
- Usually, mark a node visited when it is first discovered.
- BFS is an important foundation for shortest paths in unweighted graphs.
Next: Finding the Shortest Path with BFS
Your turn to try
Why mark a node visited when you add it to the queue instead of waiting until you remove it?
Ready? Open to see the explanation
Marking it on discovery prevents multiple predecessors from adding the same node to the queue.