问题
I am learning Dijkstra's algorithm and had a basic query. I have a graph that looks as follows..(non-negative nodes):
A---2-----B------16------D-----3-------F
* *
* *
3 4
* *
C----------2---------------------------E
Not clear from above graph display, but AC has a distance of 3 and EF has a distance of 4.
I am interested in finding shortest path between A and F.
Consider destination node F. When we consider its nearest node, we get D (DF has weight 3 and EF 4). However, when we follow that path, we get the shortest path as: A,B,D,F (total distance: 19).
A quick observation tells us that the shortest path is actually A,C,E,F (distance: 9). However, since in the 1st step, E was more distant than D, we followed D.
Am I missing something here? Dijkstra's algorithm is clearly not showing the right result here.
回答1:
Yes Dijkstra's always gives shortest path when the edge costs are all positive. However, it can fail when there are negative edge costs.
回答2:
Yes, you are missing something. Have a look at step 4 below.
- The first step would be to mark D with tentative distance 3 and E with tentative distance 4.
- The next step would select D as it is the non visited node with the lowest tentative distance
- Then you would mark all non-visited nodes from D with their distances (mark B with tentative distance 19 (3 + 16))
- Then select the next non-visited node with the lowest tentative distance. This would select E (4)
- Mark all of E's nodes with their tentative distance. C gets marked as 6 (4+2).
- Then select the next non-visited node with the lowest tentative distance. This would select C (6)
- Mark all of C's nodes with their tentative distance. A gets marked as 9 (6+3).
Stop as you have reach A with a distance of 9.
回答3:
The algorithm works just fine with your graph. It must be a bug in your implementation.
Visit A
-Set B distance = 0 + 2 = 2, previous = A
-Set C distance = 0 + 3 = 3, previous = A
Visit B
-Set D distance = 2 + 16 = 18, previous = B
Visit C
-Set E distance = 3 + 2 = 5, previous = C
Visit E
-Set F distance = 5 + 4 = 9, previous = E
Visit F
-Set D distance = 9 + 3 = 12, previous = F // you can early-out here if you want
Visit D
-Alternate distance to F: 18 + 3 = 21 (fail since current distance, 9, is smaller)
Shortest path = F.previous = E, E.previous = C, C.previous = A
= A, C, E, F
回答4:
I doubt if you really understand the algorithm. Take a look at this: https://www.youtube.com/watch?v=XB4MIexjvY0
Then implement it starting from vertex A.
Dijkstras Algorithm finds the shortest path from any given node to all other nodes, only if the edges are non-negative.
来源:https://stackoverflow.com/questions/22625922/does-dijkstras-algorithm-give-shortest-path-always