这是我使用深度优先搜索实现图的reachable()。它寻找从顶点 1 (v1) 到另一个顶点 (v2) 的可能路径,我得到了一些正确的结果,有些结果是错误的。我已经尝试了尽可能多的方法来调试,但我无法弄清楚哪里出了问题。任何帮助表示赞赏。谢谢
public boolean isReachable(V v1, V v2) {
Stack<V> path = new Stack<V>();
return isReachableHelper(v1, v2, path);
}
}
public boolean isReachableHelper(V v1, V v2, Stack<V> path){
path.push(v1);
v1.setVisited(true); //set the vertex as being visited
if (v1.vertex().equals(v2.vertex())){ //check whether vertex' values are equal
return true;
}
//loop through all vertex that are neighbors of v1
for (V neighbor : super.neighbors(v1)){
if (!neighbor.visited ){ //if the neighbor is not visited before
return isReachableHelper(neighbor, v2, path); //recursive call
}
}
path.pop(); //no path was found
return false;
}