An application for using queues.
Breadth-First Search (BFS) – Step-by-Step Description
- Initialization
- Create an array
distto store the shortest distance from the source node to every other node. - Set every entry in
distto a very large value (∞) to mean “unvisited”. - Create an empty queue
Q. - Set
dist[source] = 0because the source is distance 0 from itself. - Place the source node into the queue.
- Create an array
- Iterative Exploration
- While the queue is not empty:
- Remove (dequeue) the front node—call it
u. - Look at every neighbor
vofu. - If
vhas not yet been visited (dist[v]is still ∞):- Set
dist[v] = dist[u] + 1(one hop farther thanu). - Enqueue
vto explore its neighbors later.
- Set
- Remove (dequeue) the front node—call it
- While the queue is not empty:
- Completion
- When the queue is empty, every reachable vertex has been visited and its shortest distance from the source is stored in
dist.
- When the queue is empty, every reachable vertex has been visited and its shortest distance from the source is stored in

