开发者

Print Bellman Ford path iteratively

I currently have a Bellman Ford algorithm set up and I am trying to print the path to that node. My current algorithm is like this:

path = new int[totaledges];
path[source] = source;
d开发者_JAVA百科istance[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());
        }   
    }

And this is how I am printing it out. It is recursive but how would I set it up so that it is iterative? I am currently getting a stack overflow error.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜