The Bellman-Ford Algorithm is a graph algorithm used to find the shortest path from a single source vertex to all other vertices in a weighted graph. It is particularly useful when the graph contains negative weight edges.
0
and all other vertices as ∞
(infinity).The Bellman-Ford algorithm can detect negative-weight cycles, which are cycles in a graph where the sum of edge weights is negative. If such a cycle exists, the algorithm reports it, preventing incorrect shortest path calculations.
Bellman-Ford is useful for finding the shortest path in graphs that contain negative-weight edges, unlike Dijkstra’s algorithm, which fails with negative weights.
The algorithm is used in network routing protocols such as RIP (Routing Information Protocol) to find the shortest paths in a network.
Consider the following weighted directed graph:
A --(4)-->
B
A --(1)-->
C
B --(-2)-->
C
C --(2)-->
D
If A
is the source vertex, the Bellman-Ford algorithm computes the shortest paths from A
to all other vertices, considering both positive and negative edge weights.
OUTPUT: Shortest distances from source 0: To vertex 0 is 0 To vertex 1 is 6 To vertex 2 is 7 To vertex 3 is 2 To vertex 4 is 4
https://drawtocode.vercel.app/problems/bellman-ford-algorithm
Loading component...
Loading component...