Bellman-Ford Algorithm in C
Last Updated :
24 May, 2024
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).
Principle of Bellman Ford Algorithm
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
- For a graph with N vertices, all the edges should be relaxed N-1 times to find the single source shortest path.
- In order to detect whether a negative cycle exist or not, relax all the edges one more time and if the shortest distance for any node reduces then we can say that negative cycle exist there.
Why relaxing of edges is N- times?
- In worst case, a shortest path between two vertices can have at most N- edges. By relaxing edges N- times the algorithm optimizes the distance estimates for all vertices, assuming the absence of negative weight cycles reachable from source vertex.
Algorithm
- 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.
C Program for Implementation of Bellman-Ford Algorithm
Here's the implementation of Bellman-Ford algorithm in C:
C
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// Define maximum number of vertices
#define MAX_VERTICES 1000
// Define infinity for initialization
#define INF INT_MAX
// Define Edge structure
typedef struct {
int source;
int destination;
int weight;
} Edge;
// Define Bellman-Ford function
void bellmanFord(int graph[MAX_VERTICES][MAX_VERTICES],
int vertices, int edges, int source)
{
// Declare distance array
int distance[MAX_VERTICES];
// Initialize distances from source to all vertices as
// infinity
for (int i = 0; i < vertices; ++i)
distance[i] = INF;
// Distance from source to itself is 0
distance[source] = 0;
// Relax edges V-1 times
for (int i = 0; i < vertices - 1; ++i) {
// For each edge
for (int j = 0; j < edges; ++j) {
// If the edge exists and the new distance is
// shorter
if (graph[j][0] != -1
&& distance[graph[j][0]] != INF
&& distance[graph[j][1]]
> distance[graph[j][0]]
+ graph[j][2])
// Update the distance
distance[graph[j][1]]
= distance[graph[j][0]] + graph[j][2];
}
}
// Check for negative cycles
for (int i = 0; i < edges; ++i) {
// If a shorter path is found, there is a negative
// cycle
if (graph[i][0] != -1
&& distance[graph[i][0]] != INF
&& distance[graph[i][1]]
> distance[graph[i][0]] + graph[i][2]) {
printf("Negative cycle detected\n");
return;
}
}
// Print shortest distances from source to all vertices
printf("Vertex Distance from Source\n");
for (int i = 0; i < vertices; ++i)
printf("%d \t\t %d\n", i, distance[i]);
}
// Define main function
int main()
{
// Define number of vertices and edges
int vertices = 6;
int edges = 8;
// Define graph as an array of edges
int graph[MAX_VERTICES][MAX_VERTICES]
= { { 0, 1, 5 }, { 0, 2, 7 }, { 1, 2, 3 },
{ 1, 3, 4 }, { 1, 4, 6 }, { 3, 4, -1 },
{ 3, 5, 2 }, { 4, 5, -3 } };
// Call Bellman-Ford function with source vertex as 0
bellmanFord(graph, vertices, edges, 0);
return 0;
}
OutputVertex Distance from Source
0 0
1 5
2 7
3 9
4 8
5 5
Complexity
Time Complexity When graph is connected
- Best Case: O(E), when distance array after 1st and 2nd relaxation are same , we can simply stop further processing
- Average Case: O(V*E)
- Worst Case: O(V*E)
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.
Similar Reads
Bellman Ford Algorithm in C++ The Bellman-Ford algorithm is a single-source shortest path algorithm that finds the shortest path from a given source vertex to all other vertices in a graph. Unlike Dijkstraâs algorithm, Bellman-Ford can handle graphs with negative edge weights, making it useful in various scenarios. In this artic
5 min read
Bellman-Ford algorithm in Python 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
3 min read
Java Program to Implement Bellman Ford Algorithm The Bellman-Ford algorithm is an essential method in graph theory and algorithms used to determine the shortest paths in a weighted graph from one vertex of origin to all other vertexes. This article will cover implementing the Bellman-Ford algorithm in Java language and also explore its intricacies
6 min read
Floyd-Warshall Algorithm in C Floyd-Warshall algorithm is a dynamic programming algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs and can handle negative weights, provided there are no negative weight cycles.In this article, we will learn
5 min read
Convex Hull Algorithm in C The Convex Hull problem is a fundamental computational geometry problem, where the goal is to find the smallest convex polygon called convex hull that can enclose a set of points in a 2D plane. This problem has various applications, such as in computer graphics, geographic information systems, and c
15+ min read
Convex Hull Algorithm in C++ The Convex Hull problem is fundamental problem in computational geometry. In this, we need to find the smallest convex polygon, known as the convex hull, that can include a given set of points in a two-dimensional plane. This problem has various applications in areas such as computer graphics, geogr
15+ min read