Bellmanフォードパスを繰り返し印刷します
-
14-11-2019 - |
質問
現在ベルマンフォードアルゴリズムを設定し、そのノードへのパスを印刷しようとしています。私の現在のアルゴリズムは次のようなものです:
path = new int[totaledges];
path[source] = source;
distance[source] = 0;
String st = "";
for (int i = 0; i < totaledges; i++)
for (int j = 0; j < edges.size(); j++) {
int newDistance = distance[edges.get(j).getSource()] + edges.get(j).getWeight();
//System.out.println(newDistance + " this is teh distance");
if (newDistance < distance[edges.get(j).getDestination()]){
distance[edges.get(j).getDestination()] = newDistance;
path[edges.get(j).getDestination()] = edges.get(j).getSource();
//System.out.println(edges.get(j).getSource());
}
}
.
そしてこれが私がそれを印刷している方法です。それは再帰的ですが、それが反復的なようにそれをどのように設定しますか?私は現在スタックオーバーフローエラーを取得しています。
static void printedges(int source, int i, int[] paths)
{
// print the array that is get from step 2
if(source!=i){
printedges(source, paths[i], paths);
}
if(i == currentEdge){
System.out.print(i);
} else{
System.out.print(i+",");
}
}
. 解決
You have your parent backlinks in path. So if you just follow those links back inside a while loop until you the source, you'll have visited the path in reverse. So as you are visiting each node in a path, put it into a simple resizable container (ArrayList works well in Java), and then reverse it and print it out when you are done.
所属していません StackOverflow