To understand this example, it is recommended to have a brief idea on Bellman-Ford single source shortest path algorithm which can be found here

In Bellman-Ford algorithm, to find out the shortest path, we need to relax all the edges of the graph. This process is repeated at most (V-1) times, where V is the number of vertices in the graph.

The number of iterations needed to find out the shortest path from source to all other vertices depends on the order that we select to relax the edges.

Let’s take a look at an example:

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/d3bdf2e6-926e-4f83-801f-8cd534d8a3ce/Untitled.png

Here, the source vertex is 1. We will find out the shortest distance between the source and all the other vertices. We can clearly see that, to reach vertex 4, in the worst case, it’ll take (V-1) edges. Now depending on the order in which the edges are discovered, it might take (V-1) times to discover vertex 4. Didn’t get it? Let’s use Bellman-Ford algorithm to find out the shortest path here:

We’re going to use this sequence:

+--------+--------+--------+--------+
| Serial |    1   |    2   |    3   |
+--------+--------+--------+--------+
|  Edge  |  3->4  |  2->3  |  1->2  |
+--------+--------+--------+--------+

For our first iteration:

  1. d[3] + cost[3][4] = infinity. It won’t change anything.
  2. d[2] + cost[2][3] = infinity. It won’t change anything.
  3. d[1] + cost[1][2] = 2 < d[2]. d[2] = 2. parent[2] = 1.

We can see that our relaxation process only changed d[2]. Our graph will look like:

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1882f535-b7f3-419d-a292-9bf976229efd/Untitled.png

Second iteration:

  1. d[3] + cost[3][4] = infinity. It won’t change anything.
  2. d[2] + cost[2][3] = 5 < d[3]. d[3] = 5. parent[3] = 2.
  3. It won’t be changed.

This time the relaxation process changed d[3]. Our graph will look like:

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/051390e6-6728-4329-9147-fc00e4e32c99/Untitled.png