Bellman-Ford Algorithm
Bellman-Ford Algorithm Explanation in 4 Points:
1. Purpose: The Bellman-Ford algorithm is used to find the shortest paths from a single source
vertex to all other vertices in a weighted graph, even if the graph contains negative weight edges.
2. Working Principle: It relaxes each edge of the graph up to |V|-1 times, where |V| is the number of
vertices. Relaxation involves updating the shortest path estimate for an edge if a shorter path is
found.
3. Negative Weight Handling: The algorithm detects negative weight cycles by checking for further
relaxation in the |V|-th iteration. If relaxation is possible, the graph contains a negative weight cycle.
4. Complexity: Its time complexity is O(VE), where V is the number of vertices and E is the number
of edges, making it suitable for dense graphs or graphs with negative weights.
Advantages of Bellman-Ford Algorithm:
1. Handles Negative Weights: Unlike Dijkstra's algorithm, Bellman-Ford works with graphs that have
negative weight edges.
2. Cycle Detection: It can detect negative weight cycles in a graph, which is crucial for certain
applications.
Disadvantages of Bellman-Ford Algorithm:
1. Less Efficient: It is slower compared to other shortest path algorithms like Dijkstra, especially for
graphs without negative weights.
2. Not Suitable for All Applications: The algorithm's high computational complexity makes it
unsuitable for very large graphs.
Example:
Graph Details:
- Vertices: A, B, C, D
- Edges with Weights:
A -> B (1), B -> C (3), A -> C (4), C -> D (2), D -> B (-2)
Steps:
1. Initialize distances: A=0, B=INF, C=INF, D=INF.
2. Relax edges for |V|-1 times:
- Iteration 1: Update distances to B=1, C=4, D=INF.
- Iteration 2: Update distances to C=3 and D=5.
- Iteration 3: Confirm no further updates, shortest paths are finalized.
3. Negative cycle check: No further updates, so no negative cycles exist.
Output:
- Shortest distances: A -> B = 1, A -> C = 3, A -> D = 5.