09 CS316 - Algorithms - Graph 3 - SSP
09 CS316 - Algorithms - Graph 3 - SSP
Graph
Single-Source Shortest Path
Assoc. Prof. Ensaf Hussein
Department Of Computer Science
01/20/2024
SHORTEST PATH
Generalize distance to weighted setting
Digraph G = (V,E) with weight function W: E →R (assigning
real values to edges)
Weight of path p = v1 →v2 →… →vk is
k 1
w( p) w(vi , vi 1 )
i 1
Shortest path = a path of the minimum weight
Applications
• static/dynamic network routing
• robot motion planning
• map/route generation in traffic 2
RELAXATION
Initialize(G,
Initialize(G,s)s)
for eachvvV[G]
foreach V[G]do
do
d[v]
d[v]:=:=;
;
[v]
[v]:=:=NIL
NIL
End
Endfor;
for;
d[s]
d[s]:=
:=00
Relax(u,
Relax(u,v,v,w)w)
ififd[v]
d[v]>>d[u]
d[u]++w(u,
w(u,v)
v)
then
then
d[v]
d[v]:=
:=d[u]
d[u]++w(u,
w(u,
v);
v); 3
[v]
[v]:=
:=uu
End
Endifif
DIJKSTRA'S ALGORITHM
10
9
2 3
s 0 4 6
5 7
2
x y
EXAMPLE
u v
1
10
10
9
2 3
s 0 4 6
5 7
5
2
x y
EXAMPLE
u v
1
8 14
10
9
2 3
s 0 4 6
5 7
5 7
2
x y
EXAMPLE
u v
1
8 13
10
9
2 3
s 0 4 6
5 7
5 7
2
x y
EXAMPLE
u v
1
8 9
10
9
2 3
s 0 4 6
5 7
5 7
2
x y
EXAMPLE
u v
1
8 9
10
9
2 3
s 0 4 6
5 7
5 7
2
x y
DIJKSTRA’S RUNNING TIME
6 1
r s t u v w
5 0
2
7
–1
–2
4
3
2
EXAMPLE
6 1
r s t u v w
5 0
2
7
–1
–2
4
3
2
EXAMPLE
6 1
r s t u v w
5 0
2 2
7 6
–1
–2
4
3
2
EXAMPLE
6 1
r s t u v w
5 0
2 2
7 6
–1 6
–2 4
4
3
2
EXAMPLE
6 1
r s t u v w
5 0
2 2
7 6
–1 5
–2 4
4
3
2
EXAMPLE
6 1
r s t u v w
5 0
2 2
7 6
–1 5
–2 3
4
3
2
EXAMPLE
6 1
r s t u v w
5 0
2 2
7 6
–1 5
–2 3
4
3
2
0 if i = s j = 0
d(i, j) = if i s j = 0
min({d(k, j–1) + w(k, i): i Adj(k)}
{d(i, j–1)}) if j > 0
i
z u v x y
1 2 3 4 5
j 0 0
1 0 6 7
2 0 6 4 7 2
3 0 2 4 7 2
4 0 2 4 7 –2
BELLMAN-FORD ALGORITHM
Dijkstra’s doesn’t work when there are negative edges:
• Intuition – we can not be greedy any more on the
assumption that the lengths of paths will only increase in
the future
Bellman-Ford algorithm detects negative cycles (returns
false) or returns the shortest path-tree
29