Skip to main content

Bellman-Ford Algorithm

1. What is the Bellman-Ford Algorithm?​

The Bellman-Ford Algorithm is used to find the shortest paths from a single source vertex to all other vertices in a weighted graph, even in the presence of negative weight edges. It can detect negative weight cycles in a graph.

2. Algorithm for Bellman-Ford Algorithm​

  1. Initialize the distances to all vertices as infinity, except the source vertex, which is 0.
  2. Relax all edges ∣Vβˆ£βˆ’1|V| - 1 times, where ∣V∣|V| is the number of vertices.
  3. Repeat one more time to detect negative weight cycles. If a shorter path is found, then a negative weight cycle exists.

3. How Does Bellman-Ford Algorithm Work?​

  1. Start with the source vertex and initialize the distances to all other vertices as infinity.
  2. Relax all edges ∣Vβˆ£βˆ’1|V| - 1 times, where ∣V∣|V| is the number of vertices. Relaxation means updating the distance if a shorter path is found.
  3. Repeat the process one more time. If a shorter path is found during this additional relaxation step, then a negative weight cycle exists.

4. Problem Description​

Given a weighted graph and a source vertex, the Bellman-Ford Algorithm aims to find the shortest paths from the source vertex to all other vertices in the graph.

5. Examples​

Example graph:

      0    1    2    3
--------------------
0 | 0 4 0 0
1 | 0 0 -1 0
2 | 0 0 0 2
3 | 0 3 0 0

Starting from vertex 0, we want to find the shortest paths to all other vertices.

6. Constraints​

  • The graph can have negative weight edges.
  • The graph may not contain any negative weight cycles reachable from the source vertex.

7. Implementation​

def bellman_ford(graph, start):
vertices = list(graph.keys())
distances = {v: float('inf') for v in vertices}
distances[start] = 0

for _ in range(len(vertices) - 1):
for u in vertices:
for v, weight in graph[u]:
if distances[u] != float('inf') and distances[u] + weight < distances[v]:
distances[v] = distances[u] + weight

for u in vertices:
for v, weight in graph[u]:
if distances[u] != float('inf') and distances[u] + weight < distances[v]:
print("Graph contains negative weight cycle")
return

return distances

8. Complexity Analysis​

  • Time Complexity: O(Vβˆ—E)O(V * E), where VV is the number of vertices and EE is the number of edges.
  • Space Complexity: O(V)O(V), for storing distances.

9. Advantages and Disadvantages​

Advantages:​

  • Can handle graphs with negative weight edges.
  • Can detect negative weight cycles.

Disadvantages:​

  • Less efficient than Dijkstra's Algorithm for graphs with non-negative weights.
  • Slower on large graphs due to the need for multiple relaxation steps.

10. Reference​