Breadth-First Search for Graph in Java

This code snippet provides a Java implementation of the Breadth-First Search (BFS) algorithm for traversing a graph. The bfsOfGraph method returns an ArrayList of integers representing the BFS traversal order of the vertices.
 avatar
unknown
java
a year ago
936 B
17
Indexable
import java.util.*;

public class Solution {

    public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
       //You can code here

       ArrayList<Integer> result = new ArrayList<>();
       boolean[] isVisited = new boolean[V];

       Queue<Integer> q1 = new LinkedList<>();

       q1.add(0);
       isVisited[0]=true;

       while(!q1.isEmpty()){

        int currNode = q1.poll();

        // if(!isVisited[currNode])
        result.add(currNode);

        isVisited[currNode]=true;

        ArrayList<Integer> neighbours = adj.get(currNode);

        System.out.println(neighbours);

        for(int neighbour : neighbours)
        {
          System.out.println(neighbour);
          if(!isVisited[neighbour]){
            q1.add(neighbour);
            isVisited[neighbour]=true;
          }
        }
       }

       return result;




       
    }
}
Editor is loading...
Leave a Comment