Java Solution BFS


#1

public class Solution {

public int solve(int A, ArrayList<ArrayList<Integer>> B) {
    if(null == B || B.isEmpty()){
        return 0;
    }
    return formGraphBFS(A, B);
}
private int formGraphBFS(int A, ArrayList<ArrayList<Integer>> graph){
    LinkedList<Integer> adj[] = new LinkedList[A + 1];
    for(int i = 1 ; i < A + 1; i++){
        adj[i] = new LinkedList<Integer>();
    }
    for(ArrayList<Integer> edges : graph){
        adj[edges.get(0)].add(edges.get(1));
    }
    return BFS(A, adj,adj[1].get(0));
}
private int BFS(int vertex, LinkedList<Integer> adj[], int start){
    boolean[] visited = new boolean[vertex + 1];
    Queue<Integer> queue = new LinkedList<>();
    queue.add(start);
    visited[start] = true;
    while(!queue.isEmpty()){
        Integer head = queue.remove();
        Iterator<Integer> i = adj[head].listIterator();
        while(i.hasNext()){
            int n = i.next();
            if (!visited[n]){
                visited[n] = true;
                queue.add(n);
            }
        }
    }
    return visited[vertex] ? 1 : 0 ;
}

}