#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Graph Algorithms

Bellman-Ford Algorithm — Working, Example and Applications

The Bellman-Ford algorithm computes the shortest path from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, Bellman-Ford can correctly handle graphs with negative edge weights, and it can also detect negative weight cycles.

How It Works

  • Initialize the distance to the source as 0 and all other vertices as infinity.
  • Relax every edge — if going through an edge gives a shorter path to a vertex, update its distance.
  • Repeat the relaxation process for (V - 1) iterations, where V is the number of vertices.
  • Perform one more pass; if any distance can still be improved, a negative weight cycle exists.
def bellman_ford(edges, num_vertices, source):
    distance = [float('inf')] * num_vertices
    distance[source] = 0

    for _ in range(num_vertices - 1):
        for u, v, weight in edges:
            if distance[u] != float('inf') and distance[u] + weight < distance[v]:
                distance[v] = distance[u] + weight

    for u, v, weight in edges:
        if distance[u] != float('inf') and distance[u] + weight < distance[v]:
            raise ValueError("Graph contains a negative weight cycle")

    return distance

Worked Example

Consider a graph with edges (A→B, 4), (A→C, 5), (B→C, -3), (C→D, 2). Starting from A, Bellman-Ford relaxes each edge repeatedly: distance to B becomes 4, distance to C is improved to 1 via B (4 + -3), and distance to D becomes 3 (1 + 2). This shows how the algorithm correctly handles the negative edge B→C.

Complexity

MetricValue
TimeO(V * E)
SpaceO(V)

Applications

  • Routing protocols such as RIP (Routing Information Protocol).
  • Detecting arbitrage opportunities in currency exchange graphs.
  • Network flow problems where edge costs can be negative.

Why V − 1 Rounds Are Always Enough

A shortest path without cycles visits each vertex at most once, so it can contain at most V − 1 edges. After the first full round of relaxation, every shortest path that uses one edge is correct. After the second round, every path with up to two edges is correct, and so on. By round V − 1 every possible simple path has been accounted for.

This also explains the final check. If a distance still drops in round V, the only way that can happen is a cycle whose total weight is negative, because going around it again keeps making the path cheaper.

A negative cycle in action

Take edges (A→B, 1), (B→C, 2), (C→D, -4) and (D→B, 1). The loop B→C→D→B adds up to 2 − 4 + 1 = −1. Every trip around it lowers the cost of reaching B, C and D, so there is no true shortest distance to them. The algorithm reports the cycle instead of returning misleading numbers.

Recovering the Path and Stopping Early

The basic version returns only distances. In real problems you usually need the route, and you can often finish well before V − 1 rounds.

def bellman_ford_path(edges, n, source):
    INF = float('inf')
    dist = [INF] * n
    parent = [None] * n
    dist[source] = 0

    for _ in range(n - 1):
        changed = False
        for u, v, w in edges:
            if dist[u] != INF and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                parent[v] = u
                changed = True
        if not changed:          # nothing improved, answers are final
            break

    for u, v, w in edges:
        if dist[u] != INF and dist[u] + w < dist[v]:
            raise ValueError("Negative weight cycle reachable from source")
    return dist, parent

def build_path(parent, target):
    path = []
    while target is not None:
        path.append(target)
        target = parent[target]
    return path[::-1]

edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)]
dist, parent = bellman_ford_path(edges, 4, 0)
print(dist)                    # [0, 4, 1, 3]
print(build_path(parent, 3))   # [0, 1, 2, 3]

The parent list stores which vertex last improved each distance. Walking it backwards from the target and reversing the list gives the route A → B → C → D from the earlier example.

Choosing Between Shortest-Path Algorithms

AlgorithmNegative edgesDetects negative cyclesTimeBest fit
Dijkstra (binary heap)NoNoO((V + E) log V)Road maps, non-negative costs
Bellman-FordYesYesO(V × E)Single source with negative weights
Floyd-WarshallYesYesO(V³)All pairs on small dense graphs

If every weight is zero or positive, Dijkstra is almost always the faster choice. Reach for Bellman-Ford when weights can be negative or when you specifically need to prove that no negative cycle exists.

Common Implementation Errors

  • Treating undirected edges carelessly. An undirected edge with negative weight acts as a two-edge negative cycle, so Bellman-Ford will always flag it.
  • Dropping the infinity check. In languages with fixed-size integers, adding a weight to a large sentinel value can overflow and create fake short paths.
  • Skipping the final pass. Without it, a graph with a negative cycle returns numbers that look valid but are wrong.
  • Thinking edge order changes the answer. It only affects how many rounds are needed, not the final distances.