hardDSA

How does the Bellman-Ford algorithm work?

844 views
01

Understand the problem

Explain Bellman-Ford and negative edges.

graphsshortest-path
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Edge relaxation + negative-cycle check
Run Playground
def bellman_ford(n, edges, source):
    INF = float('inf')
    dist = [INF] * n
    dist[source] = 0
    for _ in range(n - 1):                      # relax V-1 times
        for u, v, w in edges:
            if dist[u] != INF and dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
    for u, v, w in edges:                        # one more pass detects a cycle
        if dist[u] != INF and dist[u] + w < dist[v]:
            return None                          # negative cycle
    return dist


# --- demo ---  edges (u, v, w); note negatives on 2->3 and 1->4
edges = [(0, 1, 6), (0, 2, 7), (1, 2, 8), (1, 3, 5),
         (2, 3, -3), (1, 4, -4), (3, 4, 9)]
print(bellman_ford(5, edges, 0))   # [0, 6, 7, 4, 2]
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.