gpt4 book ai didi

java - BFS方法重复显示空指针异常

转载 作者:行者123 更新时间:2023-11-30 05:38:25 25 4
gpt4 key购买 nike

在我的作业中我必须体现Bfs和Edge方法

在 BFS 方法中,我必须使用队列来存储访问过的边缘

在 Edge 方法中我必须存储数组矩阵

如果我输入,它会显示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

最佳答案

可能是由于拼写错误造成的:

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

应该是:

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

关于java - BFS方法重复显示空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com