Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
Graph-Based Algorithms: CSE373: Design and Analysis of Algorithms
Graph-Based Algorithms
CSE373: Design and Analysis of Algorithms
Shortest Path Problems
Modeling problems as graph problems:
Road map is a weighted graph:
vertices = cities
edges = road segments between cities
edge weights = road distances
Goal: find a shortest path between two vertices (cities)
Shortest Path Problems
What is shortest path ?
shortest length between two vertices for an unweighted graph:
smallest cost between two vertices for a weighted graph:
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
3
• Weight function w : E → R 4
2 1
s 0
2 7
• Weight of path p = v0, v1, k. . . , vk 5 3
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:
A weighted, directed graph G = (V, E) vj
pij pjk
A weight function w: E R, v1
p1i
A shortest path p = v1, v2, . . . , vk from v1 to vk pij’ vk
A subpath of p: pij = vi, vi+1, . . . , vj, with 1 i j k
vi
Then: pij is a shortest path from vi to vj
p1i pij pjk
Proof: p = v1 vi vj vk
RELAX(u, v, w) RELAX(u, v, w)
u v u v
2 2
5 7 5 6
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
Practice
Dijkstra (G, w, s) – Time Complexity
1. INITIALIZE-SINGLE-SOURCE(V, s) (V)
2. K ←
3. Q ← V[G] (V) time to build min-heap
6. K ← K {u}
7. for each vertex v Adj[u]
8. do RELAX(u, v, w) (E) times, (TD) each time
u
s pvu
K
v another path to u, via v
Dijkstra’s: Proof (Contd.)
• The weight of this path, w(p) = d[v]+w(pvu) ³ d[v], since
w(pvu) ³ 0 (because edge weights are non-negative).
u d[u] £ d[v]
s pvu
K
v another path to u, via v