Bellman-Ford algorithm

Let's talk about algorithms!

Moderator: Board moderators

Post Reply
r.z.
Learning poster
Posts: 56
Joined: Thu Jun 05, 2003 1:57 pm

Bellman-Ford algorithm

Post by r.z. »

I'm new with graph algoithm and I just start reading about graphs

but I'm al little bit confused about Bellman-Ford algorithm
I still can't understand how it works.....

can anyone help me.....
cypressx
New poster
Posts: 41
Joined: Sun Jul 04, 2004 12:16 pm

Post by cypressx »

Hello. Firstly my advice is to read more and more than once .. if you don`t understand something from the first time u should reread it ! :)

So about Ford-Bellman :

it is based on the inequality of the triangle :
the sum of no matter which to sides are bigger than the third. so if d(i,j) is the distance between vertex i and vertex j we can write down all the inequalities for i , j , and k as follows :
d(i,k) + d(k,j) <= d(i,j);
d(i,j) + d(j,k) <= d(i,k);
d(k,i) + d(i,j) <= d(k,j);
d(j,k) + d(k,i) <= d(j,i);
d(k,j) + d(j,i) <= d(k,i);
d(j,i) + d(i,k) <= d(j,k);
in case it is an oriented graph we have that d(x,y) = d(y,x) so we don`t need the last 3 equalations.

so let`s continue and have the algorithm :
1.) We have one array D,at the end D will contain the length of the minimal way from s to any other vertex i. We inicialize D = A[s] for every vertex connected with s;
2.) So we use the inequalities of the triangle(which I wrote above) and try to optimize D for every i connected with s - this way :
for every if D > D[j] + A[j] then D = D[j] + A[j];

so here is the sample C++ Code
for(k=1;k<=n-2;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(D > D[j] + A[j]) D[i] = D[j] + A[j][i];

Hope I helped and u got it !

P.S. u`d better study Floyd because it is a better algo for the same thing !
Keep studying
Maniac
Experienced poster
Posts: 105
Joined: Tue Oct 14, 2003 3:24 pm
Location: Utrecht, Holland

Post by Maniac »

P.S. u`d better study Floyd because it is a better algo for the same thing !
I don't totally agree: Floyd-Warshall is order V^3 whereas Bellman-Ford is V.E which can be better. Both have the advantage of allowing negative edge-weights.
Post Reply

Return to “Algorithms”