Bellman Ford’s Algorithm

Maryann Gitonga
2 min readSep 4, 2023

--

How it works

Imagine you’re planning a road trip using a navigation app. You start by entering your current location as the source and your destination as the target destination. You begin at your current location (the source) and create a list of candidate routes, just like in Dijkstra’s Algorithm.

However, Bellman-Ford’s algorithm can handle scenarios where the roads have positive or even negative weights, signifying advantages or disadvantages along the way. This is particularly useful when the road conditions might not always be favourable.

Now, instead of simply picking the shortest or quickest route, the algorithm takes an iterative approach. It explores various routes repeatedly, just like you might re-evaluate your travel options during a trip if new information or conditions arise.

Each time the algorithm goes through this iterative process, it tries to improve the routes it knows about. It doesn’t mind going over the same paths multiple times if it can lead to a better result. This persistence ensures that it eventually converges to the best path, even when there are negative weight edges in the graph.

The “relaxation” step of the algorithm uses the same formular used in Dijkstra’s Algorithm to update the cost of vertex v.

Formula used at the relaxation step.
Illustration of the Bellman Ford’s Algorithm

Benefits

  1. Handling Negative Edge Weights: It efficiently manages graphs with negative edge weights, making it suitable for scenarios where costs can be negative.
  2. Detecting Negative Weight Cycles: It can identify negative weight cycles in a graph, which is crucial for decision-making and preventing infinite loops in algorithms.

Real-life application

Logistics companies rely on algorithms like Bellman-Ford’s to efficiently optimize their delivery routes, adapting to real-time conditions such as traffic delays.

Simple Code Illustration

Where next?

--

--

Maryann Gitonga

A Software Engineer who loves trying out different tooling & engineering concepts in Back-end Engineering & DevOps. An explorer in the ML world too!