LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Dijkstra's algorithm (https://www.linuxquestions.org/questions/programming-9/dijkstras-algorithm-902655/)

ddebbie90 09-12-2011 05:09 PM

Dijkstra's algorithm
 
hello,
i'm trying to implement the dijkstra's algorithm in c but i face some problems.My algorithm is implemented to follow the edge with the minimum weight. For example, i am in a node that is connected to the node i want to go, but because the edge has more weight than another edge to a node that is not connected to the node i want to go, the algorithm follows the wrong path. I think i need one more condition, but i can figure out one. Somebody to help? :D

johnsfine 09-12-2011 06:12 PM

Quote:

Originally Posted by ddebbie90 (Post 4470062)
For example, i am in a node that is connected to the node i want to go, but because the edge has more weight than another edge to a node that is not connected to the node i want to go, the algorithm follows the wrong path.

If I understand what you just wrote, then that is correct behavior.

Assume you are at node A and your destination is B.

There is an edge of cost 6 from A to B.
There is an edge of cost 2 from A to C.
There is an edge of cost 1 from C to D.
There is an edge of cost 2 from D to B.

So the low cost path from A to B is through C.

When you are at A, you don't know whether that path from C to B exists. So the search algorithm correctly tries C first to see if such a path exists.

If there isn't an optimal path through C, the algorithm will later find the direct path from A to B.

ta0kira 09-12-2011 10:03 PM

Are you using a queue of vertices already visited? Every time you encounter a vertex insert it into the queue, prioritized by the distance it took to get there on that particular path. Keep visiting and popping the head vertex in the queue and add the vertices its connected to to the queue. Once a vertex is encountered in the queue it can be marked as "done", i.e. the shortest path to it has been found, and once you encounter your endpoint at the head of the queue you're done.
Kevin Barry


All times are GMT -5. The time now is 06:00 AM.