Domanda

Attualmente ho un algoritmo Ford Bellman impostato e sto cercando di stampare il percorso verso quel nodo.Il mio attuale algoritmo è così:

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());
        }   
    }
.

Ed è come lo sto stampando.È ricorsivo ma come lo avrei impostato in modo che sia ibrativo?Attualmente sto ottenendo un errore di overflow stack.

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+",");
    }
}
.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top