Lab 2 - Bellman Ford Algorithm
Lab 2 - Bellman Ford Algorithm
Bellman-Ford Algorithm
Most. Kaniz Fatema Isha
Md Mehrab Hossain Opi
Problem with Dijkstra 2
• Previously we learned Dijkstra’s Algorithm.
• Do you know what is the problem with this algorithm.
• Consider the following graph.
2
2 -2
1 2 3
-5
4
• Dijkstra’s algorithm does not work if the graph contains a negative cycle.
• Going through a cycle reduces path length and produces wrong result.
• Today we will learn a new algorithm that works on graph with negative cycles.
• The algorithm is called Bellman-Ford Algorithm.
The process of relaxing an edge (u,v) consists of testing whether going through vertex u
improves the shortest path to vertex v found so far and, if so, updating distance[v]
• In Dijkstra’s Algorithm, we only used the outgoing edges of a selected node in each
iteration.
• Hope you can remember it.
• But in Bellman-Ford algorithm, we will use all the edges in each iteration.
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
1 4
2 6 10 2
0 3 6
6 1 6
15
2 5
• A path with more than 𝑉−1 edges would necessarily involve revisiting some vertices,
implying a cycle.
1
The function returns True
4 if no negative cycle exists.