Bellman-Ford algorithm — DP approach, negative cycles detection, O(VE)
3.5.11· Coding › Graphs
Bellman-Ford HAI KYA?
KYUN chahiye yeh (jab Dijkstra exist karta hai)? Dijkstra assume karta hai ki ek baar koi node "finalize" ho jaaye, toh koi future path usse beat nahi kar sakta — yeh tabhi sach hai jab saare edges hon. Ek negative edge ek zyada hops wale path ko baad mein sasta bana sakta hai, jo Dijkstra ki greedy promise tod deta hai. Bellman-Ford koi greedy commitment nahi karta; woh bas tab tak relax karta rehta hai jab tak kuch improve nahi hota.
KAISE: DP derivation scratch se
Chaliye ise derive karte hain, memorize nahi.
Subproblem define karo:
Base case (KYUN): edges ke saath aap sirf par reh sakte ho.
Transition (KYUN): tak ka ek path jo edges use karta hai, ya toh:
- edges use karta hai (kuch add nahi), ya
- kisi neighbor tak edges mein path leta hai, phir edge .
par KYUN rukein? Ek shortest path jisme koi negative cycle nahi hai woh simple hota hai (koi repeated vertex nahi), toh usmein at most vertices aur isliye at most edges hote hain. Toh hi sahi answer hai.
Relaxation = transition disguise mein
Humein 2D table ki zaroorat nahi hai. Ek array dist[] rakho aur "relax" karo:
relax(u, v, w): if dist[u] + w < dist[v]: dist[v] = dist[u] + w
Saare edges par ek full pass chalana = ko (kam se kam) ek se badhana. passes karna convergence guarantee karta hai.

KAISE: negative cycle detection
Pseudocode (pura)
def bellman_ford(V, edges, src):
dist = [float('inf')] * V
dist[src] = 0
# V-1 relaxation passes
for _ in range(V - 1):
updated = False
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
updated = True
if not updated: # early exit optimization
break
# one extra pass -> detect negative cycle
for u, v, w in edges:
if dist[u] != float('inf') and dist[u] + w < dist[v]:
return None # negative cycle reachable
return distdist[u] != inf guard KYUN? inf + w phir bhi inf hi hai; guard ke bina aap kabhi galat relax nahi karte, lekin yeh spurious updates aur fixed-width integers wali languages mein overflow avoid karta hai.
Worked Example 1 — normal graph with a negative edge
Vertices ; edges: . Source .
| pass | dist[0] | dist[1] | dist[2] | dist[3] |
|---|---|---|---|---|
| init | 0 | ∞ | ∞ | ∞ |
| 1 | 0 | 4 | 1 (via 1→2, ) | 3 |
| 2 | 0 | 4 | 1 | 3 |
- Pass 1 mein dist[2]=1 kyun mila, 5 nahi? Order matter karta hai: humne pehle relax kiya (dist[1]=4), phir ne use kiya → , jo direct se better hai.
- Pass 2 mein kuch KYUN nahi badla? Pehle se converge ho chuka hai; early-exit
breaktrigger ho jaata hai. saare passes ki zaroorat nahi thi.
Answer: .
Worked Example 2 — negative cycle
Edges: . Source .
Cycle ka weight hai.
- passes ke baad, dist girti rehti hai.
- Detection KYUN fire hoti hai: extra pass phir bhi koi edge relax karta hai (jaise dist[0] improve karta hai). → negative cycle report karo.
Yeh step KYUN important hai: yahaan distances meaningless hain, isliye humein numbers nahi, ek flag return karna chahiye.
Common mistakes
Recall Feynman: ek 12-saal ke bachche ko samjhao
Socho cities ke beech travel karne ki prices hain, jahaan kuch roads tumhe paisa deti hain (negative cost). Tum ghar se har city tak ka sabse sasta rasta chahte ho. Tum "abhi tak ka sabse sasta jaana cost" ko update karte rehte ho, baar baar har road check karke. Poora map (cities ki sankhya − 1) baar check karne ke baad, prices girna band ho jaati hain — yahi tumhara answer hai. Lekin agar ek loop of roads hai jo har chakkar net paisa deti hai, toh tumhari cost kabhi girna band nahi hoti (free money forever!). Toh agar ek aur full check phir bhi koi price girata hai, tum chillate ho "ek money-loop hai!" — woh ek negative cycle hai.
Recall checks
Flashcards
Bellman-Ford time complexity
Bellman-Ford DP subproblem
Why relax times
Bellman-Ford transition
How to detect a negative cycle
Which negative cycles does it detect
Why Dijkstra fails with negative edges
Base case of Bellman-Ford DP
Early-exit optimization
Trick to detect ALL negative cycles
Connections
- Dijkstra's Algorithm — tez () lekin non-negative edges chahiye
- Dynamic Programming — Bellman-Ford "edges used" par DP hai
- Floyd-Warshall — all-pairs version, negatives bhi handle karta hai,
- Shortest Path Problem
- Negative Weight Cycles
- Graph Relaxation
- SPFA — Bellman-Ford ka queue-based optimization