How is a queue used in BFS (breadth-first search)?
In the BFS (Breadth-First Search) algorithm, a queue is used to store the vertices that need to be visited in the order they are discovered.
The essence of BFS
The algorithm traverses the graph layer by layer: first all vertices at distance 1 from the starting one, then at distance 2, and so on.
The role of the queue
- First, the starting vertex is placed into the queue.
- While the queue is not empty:
- a vertex is removed from the front of the queue (
dequeue), - all its unvisited neighbors are added to the end of the queue (
enqueue).
- This process continues until all reachable vertices have been processed.
Why a queue specifically
A queue guarantees FIFO order: all vertices of one level are processed before the vertices of the next.
This is exactly why BFS traverses the graph layer by layer, unlike DFS, which uses a stack and goes deep.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.