« previous | Friday, October 12, 2012 | next »
Shortest Paths
Weighted Graph (no negative weights)
If all weights are same, BFS would give shortest path.
Algorithm makes use of a priority queue
Dijkstra's Single Source Shortest Path Algorithm
- Assume all edge weights are nonnegative
- Similar to Prim's MST algorithm (greedily choose the lightest edge)
- Keep an estimate
of the shortest path distance from
to 
- Use
as the key in a priority queue
- When
is added to the tree, check each of
's neighbors
to see if
provides
with a cheaper path from
: compare
to 
def dijkstra_sssp graph, source
pq = PriorityQueue.new
graph.each_vertex do |v|
v.distance = Float::INFINITY
pq.insert v.distance, v
end
source.distance = 0
until pq.empty?
u = pq.extract_min
u.neighbors.each do |v|
if u.distance + graph.weight(u,v) < v.distance
v.distance = u.distance + graph.weight(u,v)
pq.decrease_key(v, v.distance)
v.parent = u
end
end
end
end
Correctness
Let
be the tree constructed after the
th iteration of the while loop:
- The nodes in
are not in 
- The edges in
are indicated by their parent variables
Claim. The pathi n
from
to
is a shortest path and has a distance
for all
Proof by induction.
Basis: When
,
is the only node in
and
.
Induction: Assume
is a correct shortest path tree. We need to show that
is a correct shortest path tree as well.
Let
be the node added in iteration
. Let
. We need to show that the path
in
from
to
is a shortest path, and has distance
.
Let
be another path from
to
. Let
be the first edge in
that leaves
.
If
is the part before
and
is the part after
, then
*
represents the shortest path, and provides a lower bound for
(any path from
to
).
Therefore,
, and the claim holds by induction on
.
Q.E.D.
Running Time
Basic running time:
- using binary heap


- using Fibonacci heap
,
, 
