简体   繁体   中英

Dijkstra algorithm not working (Adjacency matrix)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM