Bellman Ford Algorithm

Graph

Bellman Ford algorithm is used to find the shortest paths from a source vertex to all other vertices of a given weighted directed graph. This algorithm will work well even if the graph has a negative weight edge.

Problem

Consider the following graph with negative weight edge.

In this tutorial we will be finding the shortest paths from the source vertex 0 to all other vertices.

Our first task is to write down the edges of the graph along with the weight.

Edge

Weight

0 --> 1

5

0 --> 2

2

1 --> 0

3

1 --> 3

4

2 --> 3

6

3 --> 0

-1

Point to note

If there are N vertices then we will iterate N - 1 times to get the shortest distance.

And we do the Nth iteration to check if there is any negative cycle.

The graph has 4 vertices so we will iterate 3 times to find shortest distance. And we will perform the 4th iteration to check if there is any negative cycle.

Note! A negative cycle in a weighted graph is a cycle whose total weight is negative.

We will need a distance array d[ ] which will hold the distance to the respective vertices from the source vertex. And a predecessor array p[ ] which will hold the predecessor of the respective vertices. Both the array will be of size N (total number of vertices).

Steps

Step 1: We start by filling the distance array d[ ] with INFINITY and since vertex 0 is the source vertex so we will set d[0] = 0.

Step 2: Next we will fill the predecessor array p[ ] with 0.

Step 3: We will relax all the edges of the graph by loop N-1 times.

Step 4: We will perform the Nth loop to check if the graph has any negative cycle.

About Relaxing Edge

Consider an edge u --> v where u is the start and v is the end vertex respectively. Relaxing an edge relax(u,v) means to find shorter path to reach v when considering edge u --> v

So, if there exists a better path to reach vertex v then, we update the distance and predecessor of vertex v.

Why perform the Nth loop

After completing iteration (N-1) we get the shortest distance. Now in order to check if there is no negative cycle we have to perform the Nth iteration.

If there is no change in the value of distance array d[ ] in the Nth loop then the graph has no negative cycle which means we can find the shortest path. Otherwise the graph has negative cycle and we cannot find the shortest path as

Solution

After performing the calculation we will get the following distance array d[ ].