2. BFS #

Created Tuesday 31 March 2020

This is also a traversal/search technique.

In constrast with DFS, here we first print all the neighbours of the current node. Then we explore each one of them. We need a queue here.

  1. We’ll use a queue for this. We’ll put the neighbours inside. When done, we’ll pop the current node.
  2. But when we see all neigbours after coming from the predeccessor, we can again put(erraneously) it in the queue. To avoid this, we use a visited array.
  3. We go through all vertices, calling BFS from it if they are absent from visited, at the same time checking if visited.size()<V. This ensures that disconnected components are also taken into account.


Implementation tip In loops check if visited.size()==V, stop if it is.

BFS.cpp


Applications