1

in my homework i must embody Bfs and Edge method

in BFS method i must use queue to memory visited edge

in Edge method i must store arraymatrix

if i input , it shows nullpointerexception

void Bfs(int v) { 
    Queue<Integer> q = new LinkedList<>();
    
    q.add(v);
    for(int i=0;i<numofnodes;i++) {
        visited[i]=false;
    }
    visited[v] = true;
    
     while(!q.isEmpty()){
            int temp = q.poll();
            System.out.print(temp + " ");
            
            for(int j = 0; j <numofnodes; j++){
                if(AdjMatrix[temp][j] == 1 && visited[j]==false){                   
                    q.add(j);                       
                    visited[j]= true;            
                    }
                }               
            }
}

   void Edge(int n1, int n2) { 
    AdjMatrix[n1][n2]=1;
    AdjMatrix[n2][n1]=1;
}

java.lang.NullPointerException

i 5

e 0 1

e 0 3

e 1 2

e 1 4

e 2 3

e 3 4

bfs 0

0 1 3 2 4

Community
  • 1
  • 1
yoon
  • 33
  • 7
  • Assuming `visited` is a `bool[]` and `AdjMatrix` is an `int[][]` (and not `Boolean[]` and `Integer[][]`), things that can be null: `visited`, `AdjMatrix`, `AdjMatrix[temp]`. – Maurice Perry May 17 '19 at 08:46
  • But there is not enough information in your question to know which one it is. – Maurice Perry May 17 '19 at 08:47

1 Answers1

1

It could come from the typo:

for(int i=0;i<numofnodes;i++) {
    visited[v]=false;
}

that should be:

for(int i=0;i<numofnodes;i++) {
    visited[i]=false;
}
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24