0

I am using the code for dijkstras algorithm from the website http://www.geeksforgeeks.org/printing-paths-dijkstras-shortest-path-algorithm/

I am using from this website because I want to be able to find the shortest path from one node to all other nodes and I also want to print out path information.

The function to print the path information is this and it is the part I'm confused about.

int printSolution(int dist[], int n, int parent[])
{
    int src = 0;
    printf("Vertex\t  Distance\tPath");
    for (int i = 1; i < V; i++)
    {
        printf("\n%d -> %d \t\t %d\t\t%d ", src, i, dist[i], src);
        printPath(parent, i);
    }
}

It says the return type is int, but it never returns anything. I take the int away and put void but then it doesn't work.

This is what I get as output when this functions has void return value:

0 -> 1 -2147483590 0 1

0 -> 2 -2147483582 0 2

0 -> 3 -2147473649 0 3

0 -> 4 -2147473649 0 4

0 -> 5 -2147473649 0 5

0 -> 6 -2147473649 0 6

0 -> 7 -2147473649 0 7

I am using the exact code from the link above.

I guess my question is why would the creator publish a function that doesn't work, and how can I change it to make it work.

  • Forget about the website. This may be helpful for your problem: http://stackoverflow.com/questions/40875191/shortest-route-modification/40875681#40875681 – A.S.H Dec 10 '16 at 22:04
  • *It says the return type is int, but it never returns anything.* -- It is undefined behavior to return nothing from a function that is declared to return something. There are a lot of these sites such as the one you linked to that show poor, buggy code that just happens to return the right answer (and the author gets praised for coming up with the right answer, even though the code is bad). – PaulMcKenzie Dec 10 '16 at 22:16

1 Answers1

1

Since you didn't post the calling context, I can't tell you why changing the returning type from int to void will make it not work. However, it is possible to compile a returning function that does not have a return statement, as explained here. (it's not good practice, though) As for why the creator would publish a function that doesn't work, well... welcome to the internet.

Based on the given output, it appears that the problem is located elsewhere in the code. The value of dist[i] for any index should not be a negative number for Dijikstra's algorithm, so I would recommend looking wherever the values of dist[i] are set.

Community
  • 1
  • 1
Travis
  • 2,135
  • 17
  • 29