![]() |
VOOZH | about |
The Bellman-Ford algorithm helps find the shortest path from one starting point to all other points in a graph, even if some paths have negative weights. It's useful for network routing problems. In this article, we will learn about the Bellman-Ford algorithm and how to implement it in C.
The Bellman-Ford algorithm finds the shortest path from one starting point to all other points in a graph. It works on graphs with weights and without weights. Like Dijkstra's algorithm, it guarantees finding the shortest path, but it's slower. Unlike Dijkstra's, it can handle graphs with negative weights. However, it can't find a shortest path if there are any negative cycles (where you can keep subtracting distance forever).
Bellman-Ford is based on Principle of Relaxation. It starts by assuming that the shortest distance to all vertices from the source vertex is infinity. Then, through the series of iterations, it update all these distances by relaxing the edges. Means finding shorter paths whenever possible.
Detecting Negative Cycles
Why relaxing of edges is N- times?
- Initialize the distance from the source to all vertices as infinite.
- Set the distance to the source itself as 0.
- Set the predecessor of all vertices as NULL.
- For each vertex, apply relaxation for all its edges.
- Repeat the relaxation process V-1 times, where V is the number of vertices in the graph.
- Relaxation is the process of updating the shortest path found so far by checking if a shorter path can be obtained by going through the vertex under consideration.
- Check for negative-weight cycles by relaxing all edges one more time.
- If we can find a shorter path, then there is a negative cycle.
- Return the shortest distance array and the predecessor array.
Here's the implementation of Bellman-Ford algorithm in C:
Vertex Distance from Source 0 0 1 5 2 7 3 9 4 8 5 5
Time Complexity When graph is connected
Time Complexity when graph is disconnected:
All the cases: O(E*(V^2))
Auxiliary Space: O(V), where V is the number of vertices in the graph.