Open In App

Bellman-Ford Algorithm in C

Last Updated : 24 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. Initialize the distance from the source to all vertices as infinite.
  2. Set the distance to the source itself as 0.
  3. Set the predecessor of all vertices as NULL.
  4. For each vertex, apply relaxation for all its edges.
  5. Repeat the relaxation process V-1 times, where V is the number of vertices in the graph.
  6. 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.
  7. Check for negative-weight cycles by relaxing all edges one more time.
  8. If we can find a shorter path, then there is a negative cycle.
  9. 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;
}

Output
Vertex   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.


Next Article
Article Tags :

Similar Reads