Introduction
- The Bellman-Ford algorithm is a single-source shortest path algorithm that can handle graphs with negative edge weights.
- It is used to find the shortest path from a source vertex to all other vertices in a weighted directed graph.
Key points to know about the Bellman-Ford algorithm:
- Purpose: To find the shortest paths from a single source vertex to all other vertices in a weighted directed graph.
- Input: A weighted directed graph represented by an adjacency list or matrix, and a source vertex.
- Output: The shortest distances from the source vertex to all other vertices, or a message indicating the presence of a negative cycle.
- Time Complexity: O( x ), where V is the number of vertices and E is the number of edges in the graph.
- Algorithm:
- Initialize the distance to the source vertex as 0 and all other vertices as infinity.
- Relax all edges times, where is the number of vertices in the graph.
- In each iteration, for each edge with weight ,
if
distance[u] + w < distance[v]
, updatedistance[v] = distance[u] + w
. - After iterations, check for negative cycles by running the relaxation step once more. If any distance value changes, there is a negative cycle in the graph.
- Relaxation: The process of updating the distance to a vertex if a shorter path is found.
- Negative Cycles: If a graph contains a negative cycle, the Bellman-Ford algorithm will detect it after iterations. In such cases, the algorithm cannot provide the shortest paths.
Why N-1 relaxations?
- In worst case, for every iteration we’ll find one value which can be used in another iteration and in turn, another iteration and so on.
- So, the final distance array is the shortest path from the source node to each of it’s nodes.
How to detect negative cycles?
-
On nth iteration, the relaxation will be done and distance array won’t get updated after that but in case, if the distance array gets updated and distance keeps on decreasing then we’ll conclude that there’s a negative cycle.
-
In every iteration the path weight will reduce to “-1”.
Code:
TC: O( x ) ⇒ where V is the number of vertices and E is the number of edges in the graph. The algorithm performs iterations, and in each iteration, it relaxes all the edges. SC: O() to store the distances array.