Skip to content

Commit 5169742

Browse files
authored
Merge pull request #537 from ushmita4/master
Bellman Ford Algorithm in C
2 parents 929a2c6 + fdb57e8 commit 5169742

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Data Structures/Graphs/Bellman Ford.c

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2+
/*The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph. Bellman Ford's Algorithm comes into the picture when there is a negative weight edge. It also detects any negative weight cycle if present.**/
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
/*Time Complexity:- O(VE)**/
6+
int Bellman_Ford(int G[20][20] , int V, int E, int edge[20][2])
7+
{
8+
int i,u,v,k,distance[20],parent[20],S,flag=1;
9+
for(i=0;i<V;i++)
10+
distance[i] = 1000//assigning infinity value to all the path initially , parent[i] = -1 ;
11+
printf("Enter source: ");
12+
scanf("%d",&S);
13+
distance[S-1]=0 ;
14+
for(i=0;i<V-1;i++)
15+
{
16+
for(k=0;k<E;k++)
17+
{
18+
u = edge[k][0] , v = edge[k][1] ;
19+
if(distance[u]+G[u][v] < distance[v]) //Checking for the shortest path or the minimum cost
20+
distance[v] = distance[u] + G[u][v] , parent[v]=u ;
21+
}
22+
}
23+
for(k=0;k<E;k++)
24+
{
25+
u = edge[k][0] , v = edge[k][1] ;
26+
if(distance[u]+G[u][v] < distance[v])
27+
flag = 0 ;
28+
}
29+
if(flag)
30+
for(i=0;i<V;i++)
31+
printf("Vertex %d -> cost = %d parent = %d\n",i+1,distance[i],parent[i]+1);
32+
33+
return flag;
34+
}
35+
int main()
36+
{
37+
int V,edge[20][2],G[20][20],i,j,k=0;
38+
printf("BELLMAN FORD\n");
39+
printf("Enter no. of vertices: ");
40+
scanf("%d",&V);
41+
printf("Enter graph in matrix form:\n");
42+
for(i=0;i<V;i++)
43+
for(j=0;j<V;j++)
44+
{
45+
scanf("%d",&G[i][j]);
46+
if(G[i][j]!=0)
47+
edge[k][0]=i,edge[k++][1]=j;
48+
}
49+
50+
if(Bellman_Ford(G,V,k,edge))
51+
printf("\nNo negative weight cycle\n");
52+
else printf("\nNegative weight cycle exists\n");
53+
return 0;
54+
}

0 commit comments

Comments
 (0)