Algorithms: Single Source Shortest Path Problem
Algorithms: Single Source Shortest Path Problem
Problem
Algorithms Given a weighted, directed graph 1
G=(V, E), with weight function 5
10
w: E → R. 1
2 8 3
Dana Shapira 3 4
Single source shortest path
Lesson #7: problem: given vertex s, for every 1
vertex vV find a shortest path 1 1 3
Single source shortest path problem 6 4
from s to v.
6 2 5
Dijkstra’s algorithm solves this
problem efficiently for the case in
which all weights are nonnegative.
1 2
x
Proof: suppose some subpath is not a shortest path
There must then exist a shorter subpath
x
< 0
u v
correct value
Question Bellman-Ford Algorithm
Can you give an example of a graph that includes BellmanFord()
Initialize d[], which
for each v V
negative weights, and does not work with Dijkstra’s d[v] = ;
will converge to
shortest-path value
algorithm? d[s] = 0;
0 4 for i=1 to |V|-1
Relaxation:
4 4 for each edge (u,v) E Make |V|-1 passes,
A B A B Relax(u,v, w(u,v)); relaxing each edge
for each edge (u,v) E
-2 if (d[v] > d[u] + w(u,v)) Test for solution
3 3 return “no solution”; Under what condition
do we get a solution?
4 3
D C D C Relax(u,v,w): if (d[v] > d[u]+w) then d[v]=d[u]+w
1 1
13 14
Relax(u,v,w): if (d[v] > d[u]+w) then d[v]=d[u]+w Relax(u,v,w): if (d[v] > d[u]+w) then d[v]=d[u]+w
15 16
Correctness of Bellman-Ford Bellman-Ford Example
Show that d[v] = (s,v) after |V|-1 passes
Consider shortest path from s to v: s 6 B -2
s v1 v2 v3 … v
A 5 E
Initially, d[s] = 0 is correct, and doesn’t change 2 -3
(Why?) 7 8 7
After 1 pass through edges, d[v1] is correct
(Why?) and doesn’t change C
9
D
After 2 passes, d[v2] is correct and doesn’t
change
…