Bellman Ford Algorithm C program


//by Hariom Yadav
//Date : 6th - 9th Nov'14
 
 
#include<stdio.h>
//#include<alloc.h>
 
struct GraphNode
{
int node_wt;
struct AdjNode *adr_of_adj_LL;
int parent_node_no;
int no_of_adj_node;
};
 
struct AdjNode
{
int node_no;
int dist_bt_node;
struct AdjNode *next_LL_adr;
};
 
#define INF 999;
 
main()
{
struct GraphNode my_all_node[5];
struct AdjNode *my_adj_node,*frnd_adj_node,*frnd;
int i,k,s_node,frnd_node_no;
 
printf("\n We are taking graph as 5 node \n");
 
//graph details..
for(i=0;i<5;i++)//number of adjacent vertex
{
printf("\n Enter total number of adjacent node to %d \n",i);
scanf("%d",&my_all_node[i].no_of_adj_node);
}
 
for(i=0;i<5;i++)
{
if(my_all_node[i].no_of_adj_node > 0)
{
for(k=0;k<my_all_node[i].no_of_adj_node;k++)
{ my_adj_node = malloc(sizeof(struct AdjNode));
my_adj_node->next_LL_adr = NULL;
 
if(k==0)//first time store adjacent address into array
{my_all_node[i].adr_of_adj_LL = my_adj_node;
frnd_adj_node = my_adj_node;
}
 
else
{frnd_adj_node->next_LL_adr = my_adj_node;
frnd_adj_node = my_adj_node;//storing address if link list extend
}
 
printf("\nEnter node no. & edge weight that is adjacent to node %d \n",i);
scanf("%d",&my_adj_node->node_no);//node name
//printf("\nEnter edge weight\n");
scanf("%d",&my_adj_node->dist_bt_node);//node distance from array node(i)
}
}
}
 
printf("\n Start from source node..");
 
for(i=0;i<5;i++)
{//initialization of node
my_all_node[i].node_wt = INF;
}
printf("\nEnter source node number \n");
scanf("%d",&s_node);
my_all_node[s_node].node_wt = 0;
 
for(i=0;i<5;i++)//node
{
for(k=0;k<my_all_node[i].no_of_adj_node;k++)//edges or link list
{
frnd = my_all_node[i].adr_of_adj_LL;
frnd_node_no = frnd->node_no;
if(my_all_node[i].node_wt + frnd->dist_bt_node < my_all_node[frnd_node_no].node_wt)
{
my_all_node[frnd_node_no].node_wt = my_all_node[i].node_wt + frnd->dist_bt_node;
 
}
frnd = frnd->next_LL_adr;
}
}
 
for(i=0;i<5;i++)//node
{
for(k=0;k<my_all_node[i].no_of_adj_node;k++)//edges or link list
{
frnd = my_all_node[i].adr_of_adj_LL;
frnd_node_no = frnd->node_no;
if(my_all_node[i].node_wt + frnd->dist_bt_node < my_all_node[frnd_node_no].node_wt)
{
printf("\n -ve Cycle found \n");
return 0;
}
frnd = frnd->next_LL_adr;
}
}
printf("\n Graph has no -ve cycle \n");
return 0;
}

Comments