Bellman-Ford Algorithm Tutorial with Python Implementation

Dr. Soumen Atta, Ph.D.
3 min readMar 11, 2024
Bellman-Ford Algorithm Tutorial with Python Implementation by Dr. Soumen Atta, Ph.D.

The Bellman-Ford algorithm is a versatile algorithm used for finding the shortest paths from a source vertex to all other vertices in a weighted graph, even in the presence of negative-weight edges. This algorithm can be applied to both directed and undirected graphs.

Overview:

The basic idea behind the Bellman-Ford algorithm is to relax edges iteratively, updating the shortest distance estimates for each vertex until convergence. The algorithm’s main strength lies in its ability to handle graphs with negative weight edges, making it suitable for a wider range of scenarios compared to Dijkstra’s algorithm.

Steps of the Bellman-Ford Algorithm:

1. Initialization:

Start by initializing the distance to the source vertex as 0 and the distances to all other vertices as positive infinity. Create an array to store the predecessor of each vertex.

distance = [float("inf")]*num_vertices
predecessor = [None]*num_vertices
distance[source] = 0

2. Relax Edges:

Iterate over all edges in the graph and relax them. Relaxing an edge means checking if there’s a shorter path to the destination vertex through the current edge.

--

--

Dr. Soumen Atta, Ph.D.
Dr. Soumen Atta, Ph.D.

Written by Dr. Soumen Atta, Ph.D.

I am a Postdoctoral Researcher at the Faculty of IT, University of Jyväskylä, Finland. You can find more about me on my homepage: https://www.soumenatta.com/

No responses yet