BFS of graph | Practice | GeeksforGeeks

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:

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:

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. 


Your task:
You don’t need to read input or print anything. Your task is to complete the function bfsOfGraph() which takes the integer V denoting the number of vertices and adjacency list as input parameters and returns  a list containing the BFS traversal of the graph starting from the 0th vertex from left to right.

Expected Time Complexity: O(V + E)
Expected Auxiliary Space: O(V)

Constraints:
1 ≤ V, E ≤ 104
0
thakuraditya62116 hours ago
public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        ArrayList<Integer> ans = new ArrayList<>();
        boolean []visited = new boolean[V];
        
        ArrayDeque<Integer> queue = new ArrayDeque<>();
        queue.add(0);
        
        while(!queue.isEmpty()){
            int rem = queue.remove();
            ans.add(rem);
            
            for(int e : adj.get(rem)){
                if(visited[e] == false){
                    visited[e] = true;
                    queue.add(e);
                }
            }
        }
        
        return ans;
0
mankesh0163 days ago
 vector<int> bfsOfGraph(int V, vector<int> adj[]) {
       // Code here
       vector<int> ans;
       int visited[V]={0};
       queue<int> q;
       
       q.push(0);
       visited[0]=true;
       
       while(!q.empty()){
           int n=q.front();
           q.pop();
           ans.push_back(n);
           vector<int> :: iterator it;
           
   for(it=adj[n].begin(); it!=adj[n].end(); it++){
               if(!visited[*it]){
                   visited[*it]=true;
                   q.push(*it);
               }
           }
       }
       
       return ans;
   }
-1
harshscode6 days ago
o(v+e) and o(v)
void bfs(int src,vector<int> &v1,vector<int> adj[],int v)   {       queue<int> q;       vector<int> vis(v+1);       q.push(0);             while(!q.empty())       {           int node=q.front();           q.pop();            v1.push_back(node);           for(auto x:adj[node])           {               if(!vis[x])               {                   q.push(x);                   vis[x]=1;               }           }       }   }   vector<int> bfsOfGraph(int v, vector<int> adj[]) {                     vector<int> v1;       bfs(0,v1,adj,v);       return v1;   }
0
jainmuskan5651 week ago
 vector<int> bfsOfGraph(int V, vector<int> adj[]) {       // we are going to use queue and visited array       queue<int> q;       vector<int>v;       bool visited[V]={0};       q.push(0);       visited[0]=true;       while(!q.empty()){           int temp= q.front();           q.pop();           v.push_back(temp);                      // check the adjacency list for that node           for(auto neighbor: adj[temp]){               if(!visited[neighbor]){                    q.push(neighbor);                    visited[neighbor]=true;               }           }       }       return v;   }
+1
aryany8711 week ago
vector<int> bfsOfGraph(int n, vector<int> adj[]) {              //TC-O(V+E), AS-O(V) - queue and visited array are used       bool visited[n] = {0};       vector<int>v; //to store the result       queue<int>q;       //source is 0       q.push(0);       visited[0]=true;              while(!q.empty()){           //pop the front node           int currNode=q.front();           q.pop();           //push the current node in the result vector           v.push_back(currNode);                  //now we will visit all the neighbours of the current node           for(auto neighbour : adj[currNode]){               if(!visited[neighbour]){                   q.push(neighbour);                   visited[neighbour]=true;               }           }       }              return v;   }
+1
subhankar3184422 weeks ago
JAVA 0.53/6.06
 
ArrayList<Integer> list = new ArrayList<>();       Queue<Integer> q = new ArrayDeque<>();       boolean []vis = new boolean[V];       vis[0] = true;       q.add(0);       while(!q.isEmpty()){           int c = q.poll();           list.add(c);           for(int i=0; i<adj.get(c).size(); i++){               int t = adj.get(c).get(i);               if(!vis[t]){                   vis[t] = true;                   q.add(t);               }           }       }       return list;
0
lilith2 weeks ago
Java Soln Bfs
class Solution {
    // Function to return Breadth First Traversal of given graph.
    public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        ArrayList<Integer> res = new ArrayList<>();
        
        boolean[] visited = new boolean[V];
        
        ArrayDeque<Integer> q = new ArrayDeque<>();
        q.add(0);
        
        while(!q.isEmpty()) {
            int rem = q.remove();
            res.add(rem);
            
            for(int e : adj.get(rem)) {
                if(visited[e] != true) {
                    visited[e] = true;
                    q.add(e);
                }
            }
        }
        
        return res;
    }
}
+2
aryanvikas0072 weeks ago
For only first component : 
 
Just use break after 1st iteration and you will get 1st component;
class Solution {
    // Function to return Breadth First Traversal of given graph.
    public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
        // Code here
        ArrayList<Integer> bfs = new ArrayList<>();
        boolean[] vis = new boolean[V];
        
        for(int i=0; i<V; i++){ 
            if(vis[i]==false){
                Queue<Integer> q = new LinkedList<>();
                q.add(i);
                vis[i] = true;
                
                while(!q.isEmpty()){
                    Integer node = q.poll();
                    bfs.add(node);
                    for(Integer it : adj.get(node)){
                        if(vis[it]==false){
                            vis[it]=true;
                            q.add(it);
                            
                        }
                    }
                }  
            }
            break;
            
        }
        return bfs;
    }
}
+1
deeptimayeemaharana062 weeks ago
code editor not working for this problem
pls check @gfg
+4
kuldeepy104593 weeks ago
 vector<int> bfsOfGraph(int V, vector<int> adj[]) {       // Code here        vector<bool>visited(V,false);        vector<int>ans;        queue<int>q;        q.push(0);        visited[0]=true;        while(!q.empty()){            int current= q.front();            ans.push_back(current);            for(auto i: adj[current]){                if(!visited[i]){                    q.push(i);                    visited[i]=true;                }            }            q.pop();        }        return ans;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.