Open In App

Bellman-Ford algorithm in Python

Last Updated : 11 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Imagine you have a map with different cities connected by roads, each road having a certain distance. The Bellman–Ford algorithm is helps you find the shortest path from one city to all other cities, even if some roads have negative lengths. In this article, we’ll take a closer look at how this algorithm works and why it’s so handy in solving everyday problems.

Implement the Bellman-Ford algorithm to find the shortest paths from a single source vertex to all other vertices in a weighted directed graph with negative weight edges.

Examples:

Input:
graph = { 'A': {'B': -1, 'C': 4}, 'B': {'C': 3, 'D': 2, 'E': 2}, 'C': {}, 'D': {'B': 1, 'C': 5}, 'E': {'D': -3} }
source = 'A'

Output:
{'A': 0, 'B': -1, 'C': 2, 'D': -2, 'E': 1}

Approach:

The Bellman-Ford algorithm works by traversing all edges |V| - 1 times, where |V| is the number of vertices. After each iteration, the algorithm relaxes all the edges. If a shorter path is found from the source to a vertex during any iteration, then the distance of that vertex is updated.

Step-by-step algorithm:

  1. Initialize distances to all vertices as infinite and the distance to the source vertex as 0.
  2. Relax all edges |V| - 1 times.
  3. If we can find a shorter path, then there is a negative weight cycle in the graph.

Below is the implementation of the algorithm:

Python3
def bellman_ford(graph, source):
    # Step 1: Initialize distances
    distances = {vertex: float('inf') for vertex in graph}
    distances[source] = 0

    # Step 2: Relax edges |V| - 1 times
    for _ in range(len(graph) - 1):
        for u in graph:
            for v, weight in graph[u].items():
                if distances[u] != float('inf') and distances[u] + weight < distances[v]:
                    distances[v] = distances[u] + weight

    # Step 3: Check for negative weight cycles
    for u in graph:
        for v, weight in graph[u].items():
            if distances[u] != float('inf') and distances[u] + weight < distances[v]:
                raise ValueError("Graph contains negative weight cycle")

    return distances


# Example
graph = {
    'A': {'B': -1, 'C': 4},
    'B': {'C': 3, 'D': 2, 'E': 2},
    'C': {},
    'D': {'B': 1, 'C': 5},
    'E': {'D': -3}
}
source = 'A'

shortest_distances = bellman_ford(graph, source)
print(shortest_distances)

Output
{'A': 0, 'B': -1, 'C': 2, 'D': -2, 'E': 1}

Time Complexity: O(V * E * E), where V is the number of vertices and E is the number of edges
Auxiliary Space: O(V)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads