Bellman Ford2
Bellman Ford2
006
Introduction to Algorithms
−2 C D 10
3
−2 8
Recall: Relaxation Algorithm
for in :
v1 v2 v3 v4 v5 v6 v7 …
8 8 4 4 2 2 1
0 ∞ ∞ ∞ ∞ ∞ ∞
Bellman & Ford
repetitions
Bellman‐Ford Algorithm
for in :
for from to :
for in :
relax : u
if : s ,
v
Bellman‐Ford Example
8 4 2 1
v1 v2 v3 v4 v5 v6 v7 …
8 8 4 4 2 2 1
0 ∞ ∞ ∞ ∞ ∞ ∞
v1 v2 v3 v4 v5 v6 v7 …
8 8 4 4 2 2 1
0 ∞ ∞ ∞ ∞ ∞ ∞
∞ ∞
1
5 A B 3
4 −1
0 s 2 t ∞
−2 C D 1
4
∞ ∞
for from to : u
for in :
s ,
relax
for in : v
if :
report that a negative‐weight cycle exists
Bellman‐Ford Analysis
for in :
for from to :
for in :
relax
for in :
if :
report that a negative‐weight cycle exists
Recall: Relaxing Is Safe
• Lemma: The relaxation algorithm maintains
the invariant that for all .
• Proof: By induction on the number of steps.
– Consider relax
u
– By induction,
– By triangle inequality, s
v
– So setting is “safe”
Bellman‐Ford Correctness
• Claim: After iteration of Bellman‐Ford,
is at most the weight of every path from
to using at most edges, for all .
• Proof: By induction on .
– Before iteration ,
– Relaxation only decreases ’s remains true
– Iteration considers all
paths with edges
when relaxing ’s s v
incoming edges
edges
Bellman‐Ford Correctness
• Theorem: If has no negative‐
weight cycles, then at the end of Bellman‐
Ford, for all .
• Proof:
– Without negative‐weight cycles,
shortest paths are always simple
– Every simple path has vertices,
so edges
– Claim iterations make
– Safety
Bellman‐Ford Correctness
• Theorem: Bellman‐Ford correctly reports
negative‐weight cycles reachable from .
• Proof:
– If no negative‐weight cycle, then previous theorem
implies , and by triangle inequality,
, so Bellman‐Ford won’t
incorrectly report a negative‐weight cycle.
– If there’s a negative‐weight cycle, then one of its
edges can always be relaxed (once one of its
values becomes finite), so Bellman‐Ford reports.
Computing
for in :
for from to :
for in : u
relax s ,
for from to :
for in : v
if :
Correctness of
• Theorem: After the algorithm,
for all .
• Proof:
– As argued before, after loop, every negative‐
weight cycle has a relaxable edge
– Setting takes limit of relaxation
– All reachable nodes also have
– Path from original to any vertex (including )
with has at most edges
– (So relaxation is impossible after loop.)
Why Did This Work So Well?
8 4 2 1
v1 v2 v3 v4 v5 v6 v7 …
8 8 4 4 2 2 1
0 ∞ ∞ ∞ ∞ ∞ ∞