# C Program to Implement Bellman Ford Algorithm

«
»

Bellman Ford Algorithm in C is used in the graph data structure to find the shortest route from a single source to every other node in the Graph. There are many more uses of the Bellman ford algorithm other than finding the shortest route/path such as Bellman-Ford can detect the presence of a negative-weight cycle in the graph itself.

Bellman ford works on graph data structure, the graph data structure is a linkage of nodes with help of edges and these edges have some weights attached to them, representing the distance or the cost to move from one node to another.

Problem Description

Write a C program to find shortest path using bellman ford algorithm.

Problem Solution

Problem Statement: Find the least cost route from a to b, c, d, and e nodes. If weights are cost to move from one node to another node. Here source node is ‘a,’ and the destination nodes are b, c, d, and e.

Solution: Bellman ford algorithm is a dynamic programming-based algorithm.

In this case, we use previously known values to identify a more optimal solution ahead.

Assume we have a graph represented by an adjacency matrix with |vertices| number of vertices and a list with edge information such as its source and destination nodes, which is indicated by the *HEAD pointer. We must find the shortest path from the source node to the destination node.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Steps to Find the Shortest Path using Bellman Ford Algorithm in C:
• First initialize the shortest path array to store the shortest path from the source node to each node in the graph. This shortest-path array is of size |vertices|.
• Then store INT_MAX to each element in the shortest path array.
• Initialize shortest_path[source]=0 as from source node to source node the cost is 0.
• Now we need to process the edges |vertives-1| times.
• Traverse each edge and see if the sum of the shortest path from the source node to that node and the cost to move from the edge’s source node to the destination node is less than the shortest path from the source node to that Edge’s destination node. This process is known as the relaxation and it is done |vertives-1| times.
Program/Source Code

Here is source code of the C Program to Implement Bellmanford Algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `/*`
2. ` * C program to Implement Bellmanford Algorithm`
3. ` */`
4. ` `
5. `#include<stdio.h>`
6. `#include<limits.h>`
7. `#include<stdlib.h>`
8. ` `
9. `// Step 1 we are here initializing the node in the map.`
10. `// It has source node data and the destination node along with the weight of the edge.`
11. `struct Edge`
12. `{`
13. `    int source;`
14. `    int destination;`
15. `    struct Egde *next;`
16. `};`
17. ` `
18. `// Step 2: This is the pointer that points to the list that contains the edges list. `
19. ` `
20. `struct Edge *HEAD=NULL;`
21. `void Insert_Edge(int, int);`
22. ` `
23. `int main()`
24. `{`
25. `    int vertices;`
26. `    // Here we are initializing the total number of nodes in the graph`
27. `    vertices = 5;`
28. `    int graph[vertices][vertices];`
29. ` `
30. `    // Here we initialised the weight to be infinite at first `
31. `    for(int i=0;i<vertices;i++)`
32. `    {`
33. `        for(int j=0;j<vertices;j++)`
34. `        {`
35. `            graph[i][j]=INT_MAX;`
36. `        }`
37. `    }`
38. ` `
39. `    // Add edges in the node `
40. `    graph=200;`
41. `    graph=-20;`
42. `    graph=100;`
43. `    graph=70;`
44. `    graph=50;`
45. `    graph=10;`
46. `    graph=40;`
47. ` `
48. `    // This will print the graph in adjacency matrix form. `
49. `    // We are using an adjacency matrix for representing the graph.`
50. `    printf("GRAPH AFTER FILLING THE NODE IS :::\n");`
51. `    for(int i=0;i<vertices;i++)`
52. `    {`
53. `        for(int j=0;j<vertices;j++)`
54. `        {`
55. `            if(graph[i][j] == INT_MAX)`
56. `            {`
57. `                printf("%-10c", '-');`
58. `            }`
59. `            else`
60. `            {`
61. `                printf("%-10d", graph[i][j]);`
62. `            }`
63. `        }`
64. `        printf("\n");`
65. `    }`
66. ` `
67. `    printf("**********************************************************************\n");`
68. `    // Inserting edges in the linked list.`
69. `    for(int i=0;i<vertices;i++)`
70. `    {`
71. `        for(int j=0;j<vertices;j++)`
72. `        {`
73. `            if(graph[i][j] != INT_MAX)`
74. `            {`
75. `                Insert_Edge(i,j);`
76. `            }`
77. `        }`
78. `    }`
79. `    int source;`
80. `    printf("Enter the source node::  ");`
81. ` `
82. `    //source is the node from where the cost is to be found for all other nodes.`
83. `    scanf("%d",&source); // Choose the source as 0 for our first test case.`
84. `    int shortest_path[vertices];`
85. `    for(int i=0;i<vertices;i++)`
86. `    {`
87. `        shortest_path[i]=INT_MAX;`
88. `    }`
89. `    shortest_path[source]=0; //As Source cost to itself is 0`
90. ` `
91. `    // This Loop Runs |VERTICES-1| Times`
92. `    for(int i=1;i<vertices;i++)`
93. `    {`
94. `        struct Edge *temp=HEAD; `
95. `        while(temp!=NULL)`
96. `        {`
97. `            //here we check if the node is reachable from the source vertex or not.`
98. `            if(shortest_path[temp->source] != INT_MAX)`
99. `            {`
100. `                if(shortest_path[temp->source] + graph[temp->source][temp->destination]`
101. `                < shortest_path[temp->destination])`
102. `                {`
103. `                    shortest_path[temp->destination]=shortest_path[temp->source]`
104. `                    + graph[temp->source][temp->destination];`
105. `                }`
106. `            }`
107. `            temp= temp->next;`
108. `        }`
109. `    }`
110. `    printf("MINUMUM COSTS FOUND AFTER APPLYING THE BELLMAN FORD ALGORITHM `
111. `            FOR SOURCE NODE [%c] COMES OUT TO BE::: \n",source+97);`
112. `    printf("*****************************************************************\n");`
113. `    for(int i=0;i<vertices;i++)`
114. `    {`
115. `        if(shortest_path[i]==INT_MAX)`
116. `        {`
117. `            printf("Node [%c] to [%c] is unreachable \n",source+97,i+97);`
118. `            continue;`
119. `        }`
120. `        else`
121. `        {`
122. `            printf("Node [%c] TO [%c] MINIMUM COST IS:: %d\n",source+97,i+97,shortest_path[i]);`
123. `        }`
124. `    }`
125. `    return 0;`
126. `}`
127. `void Insert_Edge(int src, int des)`
128. `{`
129. `    struct Edge *ptr = (struct Edge*)malloc(sizeof(struct Edge));`
130. `    struct Edge *temp=HEAD;`
131. `    ptr->source=src;`
132. `    ptr->destination=des;`
133. `    if(HEAD==NULL)`
134. `    {`
135. `        HEAD=ptr;`
136. `        HEAD->next=NULL;`
137. `    }`
138. `    else`
139. `    {`
140. `        while(temp->next!=NULL)`
141. `        {`
142. `            temp=(struct Edge*)temp->next;`
143. `        }`
144. `        temp->next=ptr;`
145. `        ptr->next=NULL;`
146. `    }`
147. `    return ;`
148. `}`
Program Explanation

1. First declare the structure to carry the edges in the linked list. It has values of source node, destination node and weight between them.
2. Then initialize an adjacency matrix with a 5 * 5 matrix (*5->vertices in the matrix).
3. Then fill the edges and store the edges in the list pointed by the head pointer.
5. Print the graph i.e., adjacency matrix.
6. In the adjacency matrix, the row represents the source node and the columns represent the destination nodes in the graph.
7. Then declare the shortest path array, which records the shortest path from the source vertex to all other vertexes in the graph. Initially, all are set to INT MAX. We set the shortest path from the source node to the source node to zero.
8. Then we iterate the process of relaxing the shortest path array with the help of edges list |vertex-1| times.
9. In the inner loop, we have iterated the linked list containing the edge information.
10. Update the value in the shortest path array if we get a smaller value in the relaxation process for any particular node.
11. Relaxation process is discussed in the algorithm approach clearly.
12. At the end we get the minimized path from the source vertex to each vertex.
13. Print the vertex in character format by using the %c format specifier. Since the ‘0’ node represents the ‘a’ node in the graph, we can convert 0 to a by adding 97 to the 0 and then printing it with the %c format specifier.
14. ‘1’ can be added to 97 and resent ‘b’. Likewise we iterated the loop and printed all the shortest paths from the source vertex.

Time Complexity: O(|Vertices -1 | * number of Edges)
Outer loop runs as many vertices are there in the graph, we also relaxation process that requires all the edges to be iterated. Thus, we conclude that the bellman ford algorithm’s time complexity is O(|Vertices -1 | * number of Edges). We can minimize the time complexity of this algorithm if we find that no change is happened after two successive iterations in the outer loop, as it shows we have reached the optimized solution.

Space Complexity: O(vertices * vertices + Edges)
we stored the graph in the 2-d adjacency matrix, which takes up quadratic space and we even made a link list to accommodate the edges in it.

Runtime Test Cases

Testcase 1: In this case, we have taken the source vertex as “a” vertex. So the source node to find the shortest path using bellman ford algorithm is “0”.

```
GRAPH AFTER FILLING THE NODE IS :::
-         200       -20       100       -
-         -         -         -         70
-         -         -         50        -
-         -         -         -         10
-         -         40        -         -
**************************************************************************************************
Enter the source node::  0
MINUMUM COSTS FOUND AFTER APPLYING THE BELLMAN FORD ALGORITHM FOR SOURCE NODE [a] COMES OUT TO BE:::
**************************************************************************************************
Node [a] TO [a] MINIMUM COST IS:: 0
Node [a] TO [b] MINIMUM COST IS:: 200
Node [a] TO [c] MINIMUM COST IS:: -20
Node [a] TO [d] MINIMUM COST IS:: 30
Node [a] TO [e] MINIMUM COST IS:: 40```

Testcase 2: In this case, we have taken the source vertex as “e” vertex. So the source node to find the shortest path using bellman ford algorithm is “4”.

```GRAPH AFTER FILLING THE NODE IS :::
-         200       -20       100       -
-         -         -         -         70
-         -         -         50        -
-         -         -         -         10
-         -         40        -         -
****************************************************************************************************
Enter the source node::  4
MINUMUM COSTS FOUND AFTER APPLYING THE BELLMAN FORD ALGORITHM FOR SOURCE NODE [e] COMES OUT TO BE:::
****************************************************************************************************
Node [e] to [a] is unreachable
Node [e] to [b] is unreachable
Node [e] TO [c] MINIMUM COST IS:: 40
Node [e] TO [d] MINIMUM COST IS:: 90
Node [e] TO [e] MINIMUM COST IS:: 0```

Testcase 3: In this case, we have taken the source vertex as “b” vertex. So the source node to find the shortest path using bellman ford algorithm is “1”.

```GRAPH AFTER FILLING THE NODE IS :::
-         200       -20       100       -
-         -         -         -         70
-         -         -         50        -
-         -         -         -         10
-         -         40        -         -
***************************************************************************************************
Enter the source node::  1
MINUMUM COSTS FOUND AFTER APPLYING THE BELLMAN FORD ALGORITHM FOR SOURCE NODE [b] COMES OUT TO BE:::
***************************************************************************************************
Node [b] to [a] is unreachable
Node [b] TO [b] MINIMUM COST IS:: 0
Node [b] TO [c] MINIMUM COST IS:: 110
Node [b] TO [d] MINIMUM COST IS:: 160
Node [b] TO [e] MINIMUM COST IS:: 70```

Points to Remember:

• Bellman ford algorithm fails if the graph has a negative weighted cycle in it.
• It works fine even if we have negative weights on the edges of the graph as long as it is not a part of a cycle.
Method 2: Implementation of Bellmanford Algorithm

This is a C Program to find shortest path using bellman ford algorithm. Given a graph and a source vertex src in graph, find shortest paths from src to all vertices in the given graph. The graph may contain negative weight edges. We have discussed Dijkstra’s algorithm for this problem. Dijksra’s algorithm is a Greedy algorithm and time complexity is O(VLogV) (with the use of Fibonacci heap). Dijkstra doesn’t work for Graphs with negative weight edges, Bellman-Ford works for such graphs. Bellman-Ford is also simpler than Dijkstra and suites well for distributed systems. But time complexity of Bellman-Ford is O(VE), which is more than Dijkstra.

Program/Source Code

Here is source code of the C Program to Implement Bellmanford Algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `#include <stdio.h>`
2. `#include <stdlib.h>`
3. `#include <string.h>`
4. `#include <limits.h>`
5. ` `
6. `int i, j;`
7. `// a structure to represent a weighted edge in graph`
8. `struct Edge`
9. `{`
10. `    int src, dest, weight;`
11. `};`
12. ` `
13. `// a structure to represent a connected, directed and weighted graph`
14. `struct Graph`
15. `{`
16. `    // V-> Number of vertices, E-> Number of edges`
17. `    int V, E;`
18. ` `
19. `    // graph is represented as an array of edges.`
20. `    struct Edge* edge;`
21. `};`
22. ` `
23. `// Creates a graph with V vertices and E edges`
24. `struct Graph* createGraph(int V, int E)`
25. `{`
26. `    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));`
27. `    graph->V = V;`
28. `    graph->E = E;`
29. ` `
30. `    graph->edge = (struct Edge*) malloc(graph->E * sizeof(struct Edge));`
31. ` `
32. `    return graph;`
33. `}`
34. ` `
35. `// A utility function used to print the solution`
36. `void printArr(int dist[], int n)`
37. `{`
38. `    printf("Vertex   Distance from Source\n");`
39. `    for (i = 0; i < n; ++i)`
40. `        printf("%d \t\t %d\n", i, dist[i]);`
41. `}`
42. ` `
43. `// The main function that finds shortest distances from src to all other`
44. `// vertices using Bellman-Ford algorithm.  The function also detects negative`
45. `// weight cycle`
46. `void BellmanFord(struct Graph* graph, int src)`
47. `{`
48. `    int V = graph->V;`
49. `    int E = graph->E;`
50. `    int dist[V];`
51. ` `
52. `    // Step 1: Initialize distances from src to all other vertices as INFINITE`
53. `    for (i = 0; i < V; i++)`
54. `        dist[i] = INT_MAX;`
55. `    dist[src] = 0;`
56. ` `
57. `    // Step 2: Relax all edges |V| - 1 times. A simple shortest path from src`
58. `    // to any other vertex can have at-most |V| - 1 edges`
59. `    for (i = 1; i <= V - 1; i++)`
60. `    {`
61. `        for (j = 0; j < E; j++)`
62. `        {`
63. `            int u = graph->edge[j].src;`
64. `            int v = graph->edge[j].dest;`
65. `            int weight = graph->edge[j].weight;`
66. `            if (dist[u] != INT_MAX && dist[u] + weight < dist[v])`
67. `                dist[v] = dist[u] + weight;`
68. `        }`
69. `    }`
70. ` `
71. `    // Step 3: check for negative-weight cycles.  The above step guarantees`
72. `    // shortest distances if graph doesn't contain negative weight cycle.`
73. `    // If we get a shorter path, then there is a cycle.`
74. `    for (i = 0; i < E; i++)`
75. `    {`
76. `        int u = graph->edge[i].src;`
77. `        int v = graph->edge[i].dest;`
78. `        int weight = graph->edge[i].weight;`
79. `        if (dist[u] != INT_MAX && dist[u] + weight < dist[v])`
80. `            printf("Graph contains negative weight cycle");`
81. `    }`
82. ` `
83. `    printArr(dist, V);`
84. ` `
85. `    return;`
86. `}`
87. ` `
88. `// Driver program to test above functions`
89. `int main()`
90. `{`
91. `    /* Let us create the graph given in above example */`
92. `    int V = 5; // Number of vertices in graph`
93. `    int E = 8; // Number of edges in graph`
94. `    struct Graph* graph = createGraph(V, E);`
95. ` `
96. `    // add edge 0-1 (or A-B in above figure)`
97. `    graph->edge.src = 0;`
98. `    graph->edge.dest = 1;`
99. `    graph->edge.weight = -1;`
100. ` `
101. `    // add edge 0-2 (or A-C in above figure)`
102. `    graph->edge.src = 0;`
103. `    graph->edge.dest = 2;`
104. `    graph->edge.weight = 4;`
105. ` `
106. `    // add edge 1-2 (or B-C in above figure)`
107. `    graph->edge.src = 1;`
108. `    graph->edge.dest = 2;`
109. `    graph->edge.weight = 3;`
110. ` `
111. `    // add edge 1-3 (or B-D in above figure)`
112. `    graph->edge.src = 1;`
113. `    graph->edge.dest = 3;`
114. `    graph->edge.weight = 2;`
115. ` `
116. `    // add edge 1-4 (or A-E in above figure)`
117. `    graph->edge.src = 1;`
118. `    graph->edge.dest = 4;`
119. `    graph->edge.weight = 2;`
120. ` `
121. `    // add edge 3-2 (or D-C in above figure)`
122. `    graph->edge.src = 3;`
123. `    graph->edge.dest = 2;`
124. `    graph->edge.weight = 5;`
125. ` `
126. `    // add edge 3-1 (or D-B in above figure)`
127. `    graph->edge.src = 3;`
128. `    graph->edge.dest = 1;`
129. `    graph->edge.weight = 1;`
130. ` `
131. `    // add edge 4-3 (or E-D in above figure)`
132. `    graph->edge.src = 4;`
133. `    graph->edge.dest = 3;`
134. `    graph->edge.weight = -3;`
135. ` `
136. `    BellmanFord(graph, 0);`
137. ` `
138. `    return 0;`
139. `}`
Runtime Test Cases
```\$ gcc BellmanFord.c
\$ ./a.out

Vertex   Distance from Source
0 		 0
1 		 -1
2 		 2
3 		 -2
4 		 1```

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”. 