Single Source Single Paths
Problem Statement
- Find shortest path from one node to all other nodes
- Shortest means lowest total weight
- Example: Shortest route between 2 cities
- Many examples: distance, cost, penalty
- Examples (from CLRSIM):
- Shortest paths may not be unique
- Paths form a tree
Variants
- Shortest path from one source to all other nodes
- Find path to single destination node
- Shortest distance between any pair of nodes in graph
- Shortest path between all pairs in graph
Assumption and Properties
- Assume graph G is directed and weighted
- Assume no negative weights
- No cycles
Optimal Substructure
- Any subpath in a shortest path is a shortest path
- Proof: if not, cut and paste the subpath and improve the larger path
Dijkstra's Algorithm
- Shortest path from source s in graph G with weights w
Dijkstra-Shortest(G, w, s)
-- initialize
for each vertex v in G loop
v.d := integer'max -- distance to source
v.p := nil -- predecessor node in path
Add v to priority queue Q
end loop
s.d := 0
S = empty set -- Set of vertices whose shortest paths have been found
while not isempty(Q) loop
u = front(Q) -- remove smallest node from queue
add u to S -- We have found shortest path to u
for each vertex v not in S and adjacent to u loop
-- Does adding edge (u,v) create a shorter path from s to v?
if v.d > u.d + w(u, v) then
v.d := u.d + w(u, v)
v.p := u
end if
end loop
end loop
Dijkstra's Algorithm - Example
- Find shortest paths from A to all nodes