DEV Community

Cover image for Bellman ford algorithm
Sankalpcreat
Sankalpcreat

Posted on

Bellman ford algorithm

Bellman ford algorithm mainly used to find the shortest path in graph but today i will try to implement with real world example some of other algorithm like*Dijkstra Algorithm* which is also use to find the shortest path but some limitation are there in Dijkstra Algorithm like it fails when there is directed graph , edges is negative to make sure Bellman ford algorithm works completely fine

Let us take a daily life example suppose you went to hill station and you chose a elevation feature in your map now from going up to down it will show negative value so here dijkstra fails to find the shortest path

Let us take an example for this

I have taken an directed 6 location A,B,C,D,E,F and there weight(distance) is negative as well as positive so to find the minimum distance bellman ford algorithm

Image description

Now from above picture we are clear with the edges and the path of destination and source as well as weight(distance)

For calculating the shortest path there is formula for it
but first we have to create a distance vector and mark source A as 0 and other as ∞(infinity) because we don't know the exact distance(weight)

Image description

Now after taking distance array we need to write formula for it and iterate upto N-1 N(represent edges) times that is difference between the bellman ford and dijkstra algorithm formula for both the algorithm is same but that N-1 iteration makes a difference between both
formula for Bellman ford algorithm is

Image description

to use this formula first make a table of source destination and distance between two

Image description

after forming these two table do the first iteration and change the distance array from infinity to the value you will see that after first iteration B-5 ,C-3,D-6,E-3,F-2
then after second iteration distance are changed

Image description

after N-1 iteration the answer for the distance array will be
A-0,B-5,C-3,D-1,E-3,F-2

Top comments (0)