Pregunta

Actualmente tengo un algoritmo de Bellman Ford, y estoy tratando de imprimir el camino a ese nodo.Mi algoritmo actual es así:

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

y así es como lo estoy imprimiendo.Es recursivo, pero ¿cómo lo configuraría para que sea iterativo?Actualmente estoy recibiendo un error de desbordamiento de pila.

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

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top