Given a weighted graph with V vertices and E edges, and a source vertex src, find the shortest path from the source vertex to all vertices in the given graph. If a vertex cannot be reached from source vertex, mark its distance as 108.
Note: If a graph contains negative weight cycle, return -1.
Bellman-Ford is a single source shortest path algorithm. It effectively works in the cases of negative edges and is able to detect negative cycles as well. It works on the principle of relaxation of the edges.
Output: [-1] Explanation: The graph contains negative weight cycle.
Approach
The Bellman-Ford algorithm works by traversing all edges |V| - 1 times, where |V| is the number of vertices. After each iteration, the algorithm relaxes all the edges. If a shorter path is found from the source to a vertex during any iteration, then the distance of that vertex is updated.
Step-by-step algorithm
Initialize distances to all vertices as infinite and the distance to the source vertex as 0.
Relax all edges |V| - 1 times.
If we can find a shorter path, then there is a negative weight cycle in the graph.
Working of Bellman-Ford Algorithm
Below is the Python implementation of the algorithm: