VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bfs-using-stl-competitive-coding/

⇱ BFS using STL for competitive coding - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

BFS using STL for competitive coding

Last Updated : 19 May, 2024

A STL based simple implementation of BFS using queue and vector in STL. The adjacency list is represented using vectors of vector. 

In BFS, we start with a node.

  1. Create a queue and enqueue source into it. 
    1. Mark source as visited.
  2. While queue is not empty, do following
    1. Dequeue a vertex from queue. Let this  be f.
    2. Print f
    3. 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). 

👁 BFS using STL for competitive coding

For more details of BFS, refer this post
The code here is simplified such that it could be used in competitive coding. 

Implementation:

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

Time Complexity: O(V+E) - we traverse all vertices at least once and check every edge.
Auxiliary Space: O(V) - for using a queue to store vertices.

Comment
Article Tags: