Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Bellman-Ford algorithm

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 1
Introduction
In Dijkstra’s shortest-path algorithm, it was assumed that
all edge weights were nonnegative numbers.
If some of the edge weights are negative, Dijkstra’s
algorithm will not work.
The reason for the failure is that once the label of a
vertex is made permanent, it cannot be changed in future
iterations.
In order to handle a graph that has both positive and
negative weights, we must ensure that no label is
considered permanent until the program halts.
Bellman-Ford algorithm overcomes the earlier mentioned
limitations.

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 2
Bellman-Ford algorithm

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 3
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] = d[u] + w(u, v)
s s
u v u v
5
2
9 5
2
6
After relaxation:
d[v]  d[u] + w(u, v)
RELAX(u, v, w) RELAX(u, v, w)

u v u v
2 2
5 7 5 6

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 4
Contd…
All the single-source shortest-paths algorithms
start by calling INITIALIZE-SINGLE-SOURCE
then relax edges
The algorithms differ in the order and how
many times they relax each edge
Traverse all the edges |V – 1| times, every time
performing a relaxation step of each edge

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 5
Contd…
A poor choice of relaxation order can lead to
exponentially many relaxations.
“Smart” order of edge relaxations like assign
label edges say e1,e2,…,em order.
Relax in this order:

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 6
Example
t 5 x
 
6 -2
-3
8 7
s 0
-4
7 2
 
9
y z
(t, x), (t, y), (t, z), (x, t), (y, x), (y, z), (z, x), (z, s), (s, t), (s, y)

t 5 x t x
Pass 1 5
 Pass 2
6 6 
6 -2 6 -2
-3 -3
8 7 8
s 0 7
s 0
-4 -4
7 2 7 2
7  7 
9 9
y z y z
Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 7
Contd…
t 5 x
Pass 2
6 
6 -2
-3
8 7
s 0
-4
7 2
7 
9
y z

Pass 3 t 5 x Pass 4 t 5 x
6 
4
11 2
6 
4
11
6 -2 6 -2
-3 -3
8 7 8 7
s 0 s 0
-4 -4
7 2 7 2
7 
2 7 
2
9 9
y z y z

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 8
Thank You…
Any Queries...?

Data Structures and Algorithms Dept. of CSE, IIT(ISM) Dhanbad November 3, 2023 9

You might also like