0

I'm trying to BFS traverse a graph but I encountered a problem. When I try to print out the values of the graph I get this error:

Cannot invoke "java.lang.Boolean.booleanValue()" because "visited[a]" is null on line 44.

public void bfs(int startingVertex) {
    Boolean[] visited = new Boolean[vertices];
    Queue<Integer> q = new LinkedList<>();
    q.add(startingVertex);
    visited[startingVertex] = true;
    while(!q.isEmpty()) {
        int v = q.poll(); 
        System.out.println(v + " ");
        for(int i=0; i<adjList[startingVertex].size(); i++) {
            int a = adjList[startingVertex].get(i);
            if(!visited[a]) {
                visited[a] = true;
                q.add(a);
            }
        }
    }
}




public class Main {
public static void main(String[] args) {
    Graph1 graph = new Graph1(4);
    graph.addEdges(0, 1);
    graph.addEdges(0, 2);
    graph.addEdges(1, 2);
    graph.addEdges(2, 3);
    graph.bfs(0);
}

}

rhino
  • 11
  • 3

0 Answers0