The BFS algorithm starts traversing the graph from the first specified vertex and visits all its neighbors (adjacent vertices) first, one layer of the graph at a time. In other words, it visits the vertices first widely and then deeply, as demonstrated by the following diagram:
These are the steps followed by the BFS algorithm, starting at vertex v:
- Create a queue Q
- Mark v as discovered (grey) and enqueue v into Q
- While Q is not empty, perform the following steps:
- dequeue u from Q
- Mark u as discovered (grey)
- enqueue all the unvisited (white) neighbors w of u
- Mark u as explored (black)
The BFS algorithm is declared ...