Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
B 210 B
A A
450
60 190
C unweighted C weighted
graph graph
200 130
D D
E E
Shortest Path Problems
• Input:
t x
• Directed graph G = (V, E) 6
3 9
• Weight func on w : E → R 3
4
2 1
s 0
• Weight of path p = v0, v1, . . . , vk 3
2 7
k 5
w( p ) w(vi 1 , vi ) 5 11
i 1
6
y z
∞ otherwise
Variants of Shortest Paths
Single-source shortest path
Given G = (V, E), find a shortest path from a given source vertex s to each
vertex v V
All-pairs shortest-paths
Find a shortest path from u to v for every pair of vertices u and v
Optimal Substructure of Shortest Paths
Given:
vj
A weighted, directed graph G = (V, E)
pij pjk
A weight function w: E R, v1
p1i
A shortest path p = v1, v2, . . . , vk from v1 to vk pij’ vk
RELAX(u, v, w) RELAX(u, v, w)
u v u v
2 2
5 7 5 6
4. while Q
2
y z
5. do u ← EXTRACT-MIN(Q) t 1 x
10
6. S ← S {u} 10 9
2 3 4 6
s 0
7. for each vertex v Adj[u] 5 7
8. do RELAX(u, v, w) 5
y
2
z
Example
t 1 x t 1 x
8
10
14 8 13
14
10 9 10 9
2 3 4 6 2 3 4 6
s 0 s 0
5 7 5 7
5
7 5 7
2 2
y z y z
t x t 1 x
1
8 13
9 8 9
10 9 10 9
2 4 2 3 4 6
s 0 3 6 s 0
7 5 7
5
5 7 5 7
2 2
y z y z
Dijkstra’s Pseudo Code
Graph G, weight function w, root s
relaxing
edges
Dijkstra (G, w, s)
1. INITIALIZE-SINGLE-SOURCE(V, s) (V)
2. S←
3. Q ← V[G] O(V) build min-heap
4. while Q Executed O(V) times
5. do u ← EXTRACT-MIN(Q) O(lgV)
6. S ← S {u}
7. for each vertex v Adj[u]
8. do RELAX(u, v, w) O(E) times; O(lgV)
Running time: O(VlgV + ElgV) = O(ElgV)
Dijkstra’s Running Time