Bellman Ford
#include<iostream>
using namespace std;
#define M 3
int cost[M][M]={ {0,5,2},
{0,0,0},
{0,-1,0}
};
int p[M],d[M],v=M;
void initialize_all_vertices(int s)
{
for(int i=0;i<v;++i)
{
d[i]=999999;
p[i]=-1;
}
d[s]=0;
}
void relax(int i,int j)
{
if(d[j]>(d[i]+cost[i][j]))
{
d[j]=d[i]+cost[i][j];
p[j]=i;
}
}
bool bellman_ford(int s)
{
initialize_all_vertices(s);
for(int k=1;k<=v-1;++k)
{
for(int i=0;i<v;++i)
{
for(int j=0;j<v;++j)
{
if(cost[i][j]!=0)
relax (i,j);
}
}
}
for(int i=0;i<v;++i)
for(int j=0;j<v;++j)
if(cost[i][j]!=0 && d[j]>(d[i]+cost[i][j]))
return false;
return true;
}
int main()
{
if(bellman_ford(0)==true)
{
cout<<endl;
for(int i=0;i<v;++i)
cout<<d[i]<<" ";
}
else cout<<"-ve weight cycle";
}
Comments
Post a Comment