Dijkstra’s Shortest Path Algorithm
- A Greedy Algorithms to find the shortest path
- Takes in a single source, finds the shortest path to all other vertices
Constraints
- Single source: Path to all vertices
- Directed or Undirected graphs
- No negative weights allowed
- No negative weight cycles allowed
Algorithm
- Maintain a set of explored nodes for which algorithm has determined length of a shortest path
- Initialize and ,
- Repeatedly
- Choose unexplored node which minimizes:
- This is the shortest total path formed by adding a node that neighbors to an existing path in
- Add to
- Set
- edge taken to get from chosen in to
- Choose unexplored node which minimizes:
Proof
Invariant: For each node length of a shortest path. Proof by induction on Base case: is easy since and Inductive Hypothesis: Assume true when for Inductive Step:
- Let be the next node added to , and let be the final edge
- A shortest path plus is an path of length
- Consider any other path . We show that it is no shorter than
- Let be the first edge in that leaves , and let be the subpath from to .
- The length of is already as soon as it reaches :
- (non-negative lengths)
- (inductive hypothesis)
- (definition of )
- (Dijkstra chose instead of )
Implementation
Critical optimizations:
- For each unexplored node, explicitly maintain a instead of computing every time
- Use a min-oriented Priority Queue to maintain which to choose
Pseudocode:
dijkstras
PriorityQueue pq
pq.add(source, 0)
for v in other verticies
pq.add(v, infinity)
while pq is not empty
p = pq.removeSmallest()
for edge from p
relax edge
relax edge from v to u with weight w
if d[u] + w < d[v]
d[v] = d[u] + w
p[v] = u
pq.changePriority(v, d[v])
Time Complexity
- time complexity if using Priority Queue
- without heap