Home > front end >  Printing Dijkstra SSSP with recursion and in reverse order
Printing Dijkstra SSSP with recursion and in reverse order

Time:03-19

I'm trying to print out the SSSP in a specific order but I'm stucked.

lets say I have 2 array:

node = [0, 1, 2, 3] pred = [-1, 2, 0, 1]

This is the code I've come up with:

void printPath (int currentNode) {
    if (pred[currentNode] == -1) {
        printf("%d\n", currentNode);
        return;
    } else {
        printf("%d-", currentNode);
        return printPath (pred[currentNode]);
    }
}

printPath(1);

This code returns the path for node 1 as: 1-2-0. When the result I want is 0-2-1.

Can this result be achieved with the recursive function I wrote?

Thanks a lot!

CodePudding user response:

Just move theprintf node statement to execute after the recursive call.

int node[] = {0, 1, 2, 3};
int pred[] = {-1, 2, 0, 1};
...
void printPath (int cnode) {
    if (-1 == pred[cnode]) {
        printf("\n%d", cnode);
        return;
    } else {
        printPath (pred[cnode]);
        printf("->%d", cnode);
    }
}
...
printPath(1);
  • Related