# What is the Bellman-Ford Algorithm?

Bellman ford algorithm is a minimization algorithm used for encountering the shortest paths like Dijkstra’s Algorithm. It is also known as the single source shortest path but the main property which makes it different from Dijkstra’s algorithm is that it works for negative edge weights as well. Bellman-Ford is mostly used in distributed systems.

## Implementation

Consider the following graph;

Explanation

• Step-01: Find the number of iterations to be performed.
• Total nodes are 6 (A, B, C, D, E, and F), and the number of iterations will be 1 less than the number of nodes which is 6 – 1 = 5.
• Step-02: Initialization
• Initialize the value of the source node with 0, and the rest of the nodes with infinity as shown below:
• Step-03: What to do in each iteration?
For each iteration, visit every edge of the graph and update values accordingly.

Now, for any edge from X to Y,

`Value of node Y = Value of node X + Edge Weight`

If this value of node Y is less than its previous value then UPDATE it. Else let the value remain unchanged. The value of a single node can be updated 2 or more times in the same iteration.

## Iteration #1

The values of nodes after the `1st iteration` are A=0, B=1, C=3, D=5, E=5, and F=4. These values will be used as current values in the next iteration.

## Iteration #2

The values of nodes after the `2nd iteration` are A=0, B=1, C=3, D=5, E=0, and F=3. These values will be used as current values in the next iteration.

## Iteration #3

Since there is no change or update in any value so there is no need to perform further iterations, this is a stopping condition. In case we don’t find this condition we will perform iterations till the number we found the Step-01 above, which was 5 in this case.

## Results

The shortest distance of each node from the source node `A` is:

• A → A: 0
• A → B: 1
• A → C: 3
• A → D: 5
• A → E: 0
• A → F: 3

## Properties of Bellman-Ford Algorithm

• Bellman-Ford algorithm uses the dynamic approach.
• It provides solutions for negative edge weights as well.

## Drawbacks of the Bellman-Ford Algorithm

• Bellman-Ford provides solutions for negative edge weights with directed graphs only.
• It takes more time to find solutions than Dijkstra’s algorithm.