Dijkstra
Dijkstra
(Dijkstra’s Algorithm)
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
• How can we find the shortest route between two
points on a map?
• Model the problem as a graph problem:
– 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)
3
Shortest Path Problems
• Input: t x
6
3 9
– Directed graph G = (V, E) 3
4
2 1
– Weight function w : E → R s 0
2 7
5 3
• Weight of path p = v0, v1, . . . , vk 5 11
k 6
w( p ) w( vi 1 , vi ) y z
i 1
∞ otherwise
• Shortest path u to v is any path p such that w(p) = δ(u, v)
4
Variants of Shortest Paths
• Single-source shortest path
– G = (V, E) find a shortest path from a given source vertex s to
each vertex v V
• Single-destination shortest path
– Find a shortest path to a given destination vertex t from each
vertex v
– Reverse the direction of each edge single-source
• Single-pair shortest path
– Find a shortest path from u to v for given vertices u and v
– Solve the single-source problem
• All-pairs shortest-paths
– Find a shortest path from u to v for every pair of vertices u and v
5
Optimal Substructure of Shortest Paths
Given: vj
pij pjk
– A weighted, directed graph G = (V, E) v1
p1i
– A weight function w: E R, pij’ vk
8
Relaxation
• Relaxing an edge (u, v) = testing whether we
can improve the shortest path to v found so far
by going through u
If d[v] > d[u] + w(u, v)
we can improve the shortest path to v
update d[v] and [v]
s s
u v u v
5
2
9
2 After relaxation:
5 6
d[v] d[u] +
RELAX(u, v, w) RELAX(u, v,w(u,
w) v)
u v u v
2 2
5 7 5 6
9
RELAX(u, v, w)
1. if d[v] > d[u] + w(u, v)
2. then d[v] ← d[u] + w(u, v)
3. [v] ← u
10
Dijkstra’s Algorithm
• Single-source shortest path problem:
– No negative-weight edges: w(u, v) > 0 (u, v) E
3. Q ← V[G] 5 7
2
4. while Q y z
t 1 x
5. do u ← EXTRACT-MIN(Q)
10
10 9
6. S ← S {u} 2 3 4 6
s 0
7. for each vertex v Adj[u] 5 7
5
8. do RELAX(u, v, w) y
2
z
12
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
13
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
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)
17
Question
• How to solve ACM534 – Frogger?
18