Bellman-Ford Algorithm

medium

Given a directed graph with V vertices (0 .. V-1) and edges edges[i] = [u, v, w] where the weight w may be negative, return the shortest distance from source 0 to every vertex. Use 100000000 for unreachable vertices. If the graph contains a negative-weight cycle, return [-1].

Hints

Dijkstra fails with negative edges — use Bellman-Ford.
Relax all edges V-1 times; a shortest path has at most V-1 edges.
One more relaxable round means a negative cycle — return [-1].

Common doubts

A simple shortest path has at most V-1 edges, and each round extends correct distances by one edge, so V-1 rounds settle them all.
If a distance can still decrease after V-1 rounds, the path must loop through a negative cycle, decreasing without bound.
Relaxing from an unreachable vertex (value BIG) would create bogus distances; skip it.

Interview follow-ups

A queue-based variant only re-relaxes vertices whose distance changed, often much faster in practice.
Mark vertices relaxed in the V-th round and propagate; those reachable from them have undefined distance.

Fun facts

  • Bellman-Ford underlies distance-vector routing protocols like RIP.
  • It's one of the few shortest-path algorithms that tolerates negative edges.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 3, edges = [[0,1,4],[0,2,5],[1,2,-3]]
Output: [0, 4, 1]
0→1→2 (4 + -3 = 1) beats the direct 0→2 = 5.
Example 2
Input: V = 3, edges = [[0,1,1],[1,2,-1],[2,0,-1]]
Output: [-1]
The cycle 0→1→2→0 has total weight -1 — a negative cycle.
Constraints

- 1 <= V <= 500 - 0 <= edges.length <= V*(V-1) - -1000 <= w <= 1000 - edges are directed

Solve this problem →