BFS of graph

Given a directed graph. The task is to do Breadth First Traversal of this graph starting from 0.
Note: One can move from node u to node v only if there's an edge from u to v and find the BFS traversal of the graph starting from the 0th vertex,
 from left to right according to the graph. Also, you should only take nodes directly or indirectly connected from Node 0 in consideration.


Example 1:

Input:
                 0
               / | \
              1  2  3
                /
               4


Output: 0 1 2 3 4
Explanation: 
0 is connected to 1 , 2 , 3.
2 is connected to 4.
so starting from 0, it will go to 1 then 2
then 3.After this 2 to 4, thus bfs will be
0 1 2 3 4.

Example 2:

Input:
              0
             / \
            1   2


Output: 0 1 2
Explanation:
0 is connected to 1 , 2.
so starting from 0, it will go to 1 then 2,
thus bfs will be 0 1 2 3 4. 



c++ implementation:

void bfi(vector<int> g[])
{  
 int vis[N];  
for(int i=0;i<N;i++)
vis[i]=0;

  queue<int>q;
  q.push(0);
  vis[0]=1;
while(!q.empty())
{ 
  int c=q.front();
  cout<<c<<" ";
  q.pop();
  for(auto x:g[c])
 {
     if(vis[x]==0)
    { 
      q.push(x);
      vis[x]=1;
     }
  } 
 }
    
}


  • Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
  • Space Complexity :O(V). 
    Since an extra visited array is needed of size V.

No comments

darkmode