From Lecture: Dijkstra’s shortest path algorithm
Dijkstra
- white:
dist == infinity
- gray:
dist < infinity
, in queue - black:
dist < infinity
, not in queue
1 | root.dist = 0; //root is the source |
v1
and v2
is on the best path iff v1.dist+d=v2.dist
Therefore, if we want to get the shortest path, we can use this algorithm to walk straight back to the graph from destination.
Performance
Total: O((V+E)lgV)
- outer loop: O(V lgV)
- once per vertex, O(V) iterations
- finding min element in the queue once: O(lg V) - BST or heap
- inneer loop: O(E lgV)
- O(E) iterations
- time to push/update priority queue: O(lg V)
Correctness
Loop Invariant:
- For every black node b, gray g:
b.dist<=g.dist
- v.dist is length of shortest interior path to v (or infinity if none) (interior path means it stays in the black region, which means it only uses black nodes)
Establishment:
no black nodes
PostCondition:
- no gray nodes
- all the nodes are black -> All paths are interior path -> shortest: interior path is actual answer
Preservation:
Application:
if you have something like condition probability which has to be multiplied to produce the correct result. But so you want to know the shortest probability there. You can just take the log of probability.
For example, suppose that we had a state machine that transitioned to new states with some given probability on each outgoing edge. The probability of taking a particular path through the graph would then be the product of the probabilities on edges along that path. We can then answer questions such as, “What is the most likely path that the system will follow in order to arrive at a given state?” by solving a shortest path problem in a weighted graph in which the weights are the negative logarithms of the probabilities, since $(−log a) + (−log b) = −log ab$.