任何人都可以帮助我如何使用Java中的广度优先搜索计算图表的访问级别?
这是我的方法,我有启动节点(str)和结束节点(目标),当循环到达目标节点时,它应该停止.
我现在想要的是计算从起始节点到结束节点的级别.
public void bfs(String str,String goal) {
int strInx = findIndex(str);
vertexList[strInx].wasVisited = true;
theQueue.insert(strInx);
int v2;
boolean bre = false;
while (!theQueue.isEmpty()) {
System.out.println(vertexList[theQueue.getFront()].label);
int v1 = theQueue.remove();
while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
vertexList[v2].wasVisited = true;
System.out.println("--V2--->"+vertexList[v2].label);
theQueue.insert(v2);
if(goal.equals(vertexList[v2].label)) {
bre=true;
break;
}
}
if(bre)
break;
}
for (int j = 0; j < nVerts; j++) {
vertexList[j].wasVisited = false;
}
}
Run Code Online (Sandbox Code Playgroud)