0

Given a directed graph, the task is to do Breadth First Traversal of this graph starting from 0.

Complete the Function bfsOfGraph() to return Breadth First Traversal of given graph.

Here, V denotes the number of vertices.

Here's the problem link

class Solution
{    
         public ArrayList<Integer> bfsOfGraph(int V , ArrayList<ArrayList<Integer>> adj)
         {    
                  ArrayList<Integer> bfs = new ArrayList<>();
                  boolean vis[] = new boolean[V+1]; 
        
                 for( int i = 1; i < V+1 ; 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);
                                   }
                            }   
                      }
                }
          }
        return bfs;
        
    }
}
risingStark
  • 1,153
  • 10
  • 17
Lucky
  • 3
  • 3

1 Answers1

0

When you know you have started (origin of the graph) from 0 then why are calling on each node (vertex) of the graph. I think you misunderstood the questions. You have to apply BFS on the Origin 0. You Might get the IndexOutOfBound Exception as well because all the vertex of the graphs is from 0 to V-1 inclusive. I can see you are treating the graph vertex as 1 to V inclusive.

public ArrayList<Integer> bfsOfGraph(int V,ArrayList<ArrayList<Integer>> adj)
    {
        Queue<Integer> queue = new LinkedList<>();
        boolean visited[] = new boolean[V];
        ArrayList<Integer> results = new ArrayList<>();
        queue.add(0);
        while(!queue.isEmpty()){
            Integer nextNode = queue.poll();
            results.add(nextNode);
            visited[nextNode] = true;
            if(adj.get(nextNode) != null){
                for(int neighbor : adj.get(nextNode)){
                    if(!visited[neighbor]){
                        queue.add(neighbor);
                        visited[neighbor] = true;
                    }
                }
            }
        }
        return results;
    }
Mukesh Kumar Gupta
  • 1,567
  • 20
  • 15