Bellman Ford

Posted: 23 Jul, 2021
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

You have been given a directed weighted graph of ‘N’ vertices labeled from 1 to 'N' and ‘M’ edges. Each edge connecting two nodes 'u' and 'v' has a weight 'w' denoting the distance between them.

Your task is to find the length of the shortest path between the ‘src’ and ‘dest’ vertex given to you in the graph. The graph may contain negatively weighted edges.

Example :

Alt text

3 3 1 3
1 2 2
1 3 2
2 3 -1
In the above graph, the length of the shortest path between vertex 1 and vertex 3 is 1->2->3 with a cost of 2 - 1 = 1.

Note :

It's guaranteed that the graph doesn't contain self-loops and multiple edges. Also the graph does not contain negative weight cycles.

Input Format :

The first line of input contains an integer ‘T’ denoting the number of test cases. Then each test case follows.

The first line of each test case contains four single space-separated integers ‘N’,  ‘M’ , ‘src’ and ‘dest’ denoting the number of vertices, the number of edges in the directed graph the source vertex and the destination vertex respectively.

The next ‘M’ lines each contain three single space-separated integers ‘u’, ‘v’, and ‘w’, denoting an edge from vertex ‘u’ to vertex ‘v’, having weight ‘w’.

Output Format :

For each test case, return an integer denoting the length of the shortest path from ‘src’ to ‘dest’. If no path is possible return 10^9. 
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.

Constraints :

1 <= T <= 10
1 <= N <= 50
1 <= M <= 300
1 <= src, dest <= N
1 <= u,v <= N
-10^5 <= w <= 10^5

Time Limit: 1 sec
Approach 1

In this algorithm, we have a source vertex and we find the shortest path from source to all the vertices.

For this, we will create an array of distances D[1...N], where D[i] stores the distance of vertex ‘i’ from the source vertex. Initially all the array values contain an infinite value, except ‘D[source]’, ‘D[source]’ = 0.

The algorithm consists of several iterations and in each iteration, we try to produce relaxation in the edges. Relaxation means reducing the value of ‘D[i]’.

For this, we will iterate on the edges of the graph let’s consider an edge (‘u’, ’v’, ’w’) :

  • If ‘D[v]’ is greater than ‘D[u]’ + ‘w’, then ‘D[v]’ = ‘D[u]’ + ‘w’.

The algorithm claims that ‘N-1’ iterations are enough to find the distances of the vertices from the source vertex. 

We also know that the graph doesn’t contain negative weight cycles. Hence we do not need to check it explicitly.


 

 Algorithm:

  • Make an array ‘D’ and initialize the array with an infinite value, except ‘D[source]’, ‘D[source]’ = 0.
  • Do ‘N’ - 1 iterations and in each iteration follow the below steps:
    • Iterate on the edges on the graph and for each edge (‘u’,’v’,’w’) update the value to ‘D[v]’, i.e., ‘D[v]’ = min(‘D[v]’, ‘D[u]+w’).
  • Return the value of ‘D[‘dest’]’.
Try Problem