BFS using STL for competitive coding
In BFS, we start with a node.
- Create a queue and enqueue source into it.
- Mark source as visited.
- While queue is not empty, do following
- Dequeue a vertex from queue. Let this be f.
- Print f
- Enqueue all not yet visited adjacent of f and mark them visited.
Below is an example BFS starting from source vertex 1. Note that there can be multiple BFSs possible for a graph (even from a particular vertex).
For more details of BFS, refer this post .
The code here is simplified such that it could be used in competitive coding.
Input: 8 10 0 1 0 2 0 3 0 4 1 5 2 5 3 6 4 6 5 7 6 7 Output: 0 1 2 3 4 5 6 7
This article is contributed by Nikhil Mahendran. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.