Reputation: 115
How can the shortest path be A,C,E,B,D when there is no path between E and B?
Upvotes: 2
Views: 4595
Reputation: 18792
Dijkstra's algorithm adds nodes to the queue in the same order as Breadth-First-Search (BFS) does: when a node is tested its immediate neighbors are added to the queue.
The difference is the way nodes are pulled out from the queue. While BFS does it in FIFO (first in first out) sequence, Dijkstra's algorithm does it by priority.
The node with the highest priority is pulled out from the queue. The priority is set by the cost to get from the origin to that node.
When the origin A is tested its immediate neighbors are added to the queue, so the queue holds 2 nodes :
B(10), C(3)
For convenience I added the cost to each node's name.
The next node to be pulled out of the queue and tested, is the one with the highest priority = lowest cost which is C. After testing C the queue looks like that:
B(7), E(5), D(11)
The cost of B was updated from 10 to 7 because a path with a lower cost (A->C->B) was found.
The next node to be pulled out of the queue is E. Testing E does not add add any of its neighbors (C,D) to the queue. C has already been tested , and D is in the queue.
The queue after pulling E out looks like that:
B(7), D(11)
B which has the highest priority (lowest cost from origin) is pulled out from the queue.
Testing B updates the cost of D to 7+2 = 9. Now we have only D in the queue:
D(9)
D is pulled out and because it it the target the search stops. The right shortest path having the cost of 9 has been found.
Upvotes: 4
Reputation: 131
Dijkstra's algorithm computes what is the lowest cost from the starting node in this case A to all other nodes in a typical implementation.
To get the complete path from node A to some other node we follow the back pointers back to A. This, is not shown in this example.
The nodes in S are arranged in the order of increasing cost from A. I am including a few resources on the topic, which might be helpful:
Upvotes: 1