我目前设置了Bellman Ford算法,我正在尝试打印到该节点的路径。我目前的算法是这样的:
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+",");
}
}
答案 0 :(得分:0)
您的路径中有您的父反向链接。因此,如果您只是在一个while循环中关注这些链接,直到您的源,您将反过来访问该路径。因此,当您访问路径中的每个节点时,将其放入一个简单的可调整大小的容器中(ArrayList在Java中运行良好),然后在完成后将其反转并打印出来。