BFS is a classic algorithm for traversing (visiting) all nodes of a graph or tree.
The easiest way to understand this algorithm is via pseudo-code and an example. The pseudo-code of BFS is as follows:
- Create a queue Q
- Mark v as visited and put v into Q
- While Q is non-empty
- Remove the head h of Q
- Mark and en-queue all (unvisited) neighbors of h
Let's assume the graph from the following diagram, Step 0:
![](/api/v2/epubs/9781789801415/files/assets/da9ace7a-fd80-4dc8-905a-278b00375fa2.png)
At the first step (Step 1), we visit vertex 0. We put this in the visited list and all its adjacent vertices in the queue (3, 1). Furthermore, at Step 2, we visit the element at the front of the queue, 3. Vertex