Skip to content

Commit 04f6b65

Browse files
committed
Create Bellman Ford.c
1 parent 557f12c commit 04f6b65

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Data Structures/Graphs/Bellman Ford.c

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
int Bellman_Ford(int G[20][20] , int V, int E, int edge[20][2])
4+
{
5+
int i,u,v,k,distance[20],parent[20],S,flag=1;
6+
for(i=0;i<V;i++)
7+
distance[i] = 1000 , parent[i] = -1 ;
8+
printf("Enter source: ");
9+
scanf("%d",&S);
10+
distance[S-1]=0 ;
11+
for(i=0;i<V-1;i++)
12+
{
13+
for(k=0;k<E;k++)
14+
{
15+
u = edge[k][0] , v = edge[k][1] ;
16+
if(distance[u]+G[u][v] < distance[v])
17+
distance[v] = distance[u] + G[u][v] , parent[v]=u ;
18+
}
19+
}
20+
for(k=0;k<E;k++)
21+
{
22+
u = edge[k][0] , v = edge[k][1] ;
23+
if(distance[u]+G[u][v] < distance[v])
24+
flag = 0 ;
25+
}
26+
if(flag)
27+
for(i=0;i<V;i++)
28+
printf("Vertex %d -> cost = %d parent = %d\n",i+1,distance[i],parent[i]+1);
29+
30+
return flag;
31+
}
32+
int main()
33+
{
34+
int V,edge[20][2],G[20][20],i,j,k=0;
35+
printf("BELLMAN FORD\n");
36+
printf("Enter no. of vertices: ");
37+
scanf("%d",&V);
38+
printf("Enter graph in matrix form:\n");
39+
for(i=0;i<V;i++)
40+
for(j=0;j<V;j++)
41+
{
42+
scanf("%d",&G[i][j]);
43+
if(G[i][j]!=0)
44+
edge[k][0]=i,edge[k++][1]=j;
45+
}
46+
47+
if(Bellman_Ford(G,V,k,edge))
48+
printf("\nNo negative weight cycle\n");
49+
else printf("\nNegative weight cycle exists\n");
50+
return 0;
51+
}

0 commit comments

Comments
 (0)