codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

23 / 65 topics
22Dijkstra's Algorithm23Bellman-Ford Algorithm24Floyd-Warshall Algorithm
Tutorials/Data Structures & Algorithms/Bellman-Ford Algorithm
🧮Data Structures & Algorithms

Bellman-Ford Algorithm

Updated 2026-04-20
3 min read

Bellman-Ford Algorithm

The Bellman-Ford algorithm is a classic and versatile shortest path algorithm used in graph theory. Unlike Dijkstra's algorithm, which works efficiently for graphs with non-negative edge weights, the Bellman-Ford algorithm can handle graphs with negative weight edges, as long as they do not contain any negative weight cycles.

In this tutorial, we will explore the Bellman-Ford algorithm in detail, including its implementation, real-world applications, and best practices. By the end of this guide, you should have a solid understanding of how to apply the Bellman-Ford algorithm to solve shortest path problems.

Overview

The Bellman-Ford algorithm was developed by Richard Bellman and Lester Ford Jr. in 1958. It is used to find the shortest paths from a single source vertex to all other vertices in a weighted graph, even when some of the edge weights are negative. The algorithm works by iteratively relaxing the edges of the graph.

Key Concepts

Relaxation

Relaxation is a process where we attempt to improve our estimate of the shortest path to a vertex. If we find a shorter path to a vertex through another vertex, we update the distance and predecessor information for that vertex.

Negative Weight Cycles

A negative weight cycle is a cycle in a graph where the sum of the weights of the edges in the cycle is negative. The Bellman-Ford algorithm can detect such cycles and report them, as they would make finding shortest paths impossible.

Algorithm Steps

  1. Initialization:

    • Set the distance to the source vertex to 0.
    • Set the distance to all other vertices to infinity (∞).
    • Set the predecessor of each vertex to null.
  2. Relaxation:

    • For each edge (u, v) in the graph, perform the following steps:
      • If distance[v] > distance[u] + weight(u, v), then:
        • Update distance[v] to distance[u] + weight(u, v).
        • Set the predecessor of v to u.
  3. Negative Weight Cycle Detection:

    • Perform a final relaxation step on all edges.
    • If any distance is updated during this step, then there is a negative weight cycle in the graph.

Pseudocode

Here is the pseudocode for the Bellman-Ford algorithm:

function bellmanFord(graph, source):
    n = number of vertices in graph
    distances = array of size n with all values set to ∞
    predecessors = array of size n with all values set to null
    distances[source] = 0

    for i from 1 to n-1:
        for each edge (u, v) in graph:
            if distances[u] + weight(u, v) < distances[v]:
                distances[v] = distances[u] + weight(u, v)
                predecessors[v] = u

    for each edge (u, v) in graph:
        if distances[u] + weight(u, v) < distances[v]:
            return "Graph contains a negative weight cycle"

    return distances, predecessors

Implementation in Python

Below is a Python implementation of the Bellman-Ford algorithm:

class Graph:
    def __init__(self, vertices):
        self.V = vertices
        self.graph = []

    def add_edge(self, u, v, w):
        self.graph.append([u, v, w])

    def bellman_ford(self, src):
        dist = [float("Inf")] * self.V
        pred = [-1] * self.V
        dist[src] = 0

        for _ in range(self.V - 1):
            for u, v, w in self.graph:
                if dist[u] != float("Inf") and dist[u] + w < dist[v]:
                    dist[v] = dist[u] + w
                    pred[v] = u

        for u, v, w in self.graph:
            if dist[u] != float("Inf") and dist[u] + w < dist[v]:
                print("Graph contains negative weight cycle")
                return

        self.print_solution(dist, pred)

    def print_solution(self, dist, pred):
        print("Vertex Distance from Source")
        for i in range(self.V):
            print(f"{i}\t\t{dist[i]}")

# Example usage
g = Graph(5)
g.add_edge(0, 1, -1)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 3)
g.add_edge(1, 3, 2)
g.add_edge(1, 4, 2)
g.add_edge(3, 2, 5)
g.add_edge(3, 1, 1)
g.add_edge(4, 3, -3)

g.bellman_ford(0)

Real-World Applications

The Bellman-Ford algorithm has several real-world applications:

  • Routing Protocols: Used in network routing to find the shortest path between nodes.
  • Finance: Used in arbitrage detection, where negative weight cycles can indicate profitable trading opportunities.
  • Transportation Networks: Used to find the most cost-effective routes for transportation.

Best Practices

  1. Graph Representation: Use an adjacency list representation for efficient edge iteration.
  2. Initialization: Ensure that all distances are initialized correctly, with the source vertex having a distance of 0 and all others set to infinity.
  3. Negative Weight Cycle Detection: Always perform the final relaxation step to detect negative weight cycles.
  4. Performance Considerations: The Bellman-Ford algorithm has a time complexity of \(O(VE)\), where \(V\) is the number of vertices and \(E\) is the number of edges. It is suitable for graphs with a moderate number of vertices and edges.

Conclusion

The Bellman-Ford algorithm is a powerful tool for finding shortest paths in graphs, especially when dealing with negative weight edges. By understanding its implementation and applications, you can effectively solve complex shortest path problems in various domains. Whether you are working on network routing, finance, or transportation networks, the Bellman-Ford algorithm provides a reliable solution.

Feel free to experiment with different graph structures and edge weights to gain a deeper understanding of how the algorithm works. Happy coding!


PreviousDijkstra's AlgorithmNext Floyd-Warshall Algorithm

Recommended Gear

Dijkstra's AlgorithmFloyd-Warshall Algorithm