Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printing Dijkstra SSSP with recursion and in reverse order

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading