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].
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.
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.
- 1 <= V <= 500 - 0 <= edges.length <= V*(V-1) - -1000 <= w <= 1000 - edges are directed
Dijkstra can't handle negative edges; Bellman-Ford can. Its guarantee: relaxing all edges V-1 times settles every shortest path, because a shortest path in a graph with no negative cycle uses at most V-1 edges, and each round pushes correct distances one edge further.
Negative-cycle detection falls out for free: after V-1 rounds, do one more. If any edge can still be relaxed, some distance is decreasing without bound — a negative cycle — so return [-1]. O(V·E).
An easy optimization: if a whole round makes no change, the distances have converged and you can stop early (and there's no reachable negative cycle).
“Can weights be negative?”
Yes — that's why Bellman-Ford, not Dijkstra.
“What signals a negative cycle?”
A relaxation still possible after V-1 rounds.
I relax all edges V-1 times; that settles every shortest path since a path has at most V-1 edges.
One more round that still relaxes means a negative cycle, so I return [-1].
Worked example — V = 3, edges [[0,1,4],[0,2,5],[1,2,-3]]
round 1: dist[1]=4, dist[2]=5, then via 1: dist[2]=4-3=1 no V-th improvement -> dist = [0, 4, 1]
A path has at most V-1 edges.
Unbounded decrease means a negative loop.
Safe to stop early.
| Full V-1 rounds | Early termination | |
|---|---|---|
| Rounds | always V-1 | stop when a round changes nothing |
| Time | O(V·E) | O(V·E) worst case, often less |
| Neg cycle | extra round check | extra round check |
Both compute the same distances and detect the same negative cycles. Full code is in the Approaches selector below.
Key takeaway
Relax all edges V-1 times to settle shortest paths; a further relaxation signals a negative cycle (return [-1]). O(V·E), with an easy early-stop when a round makes no change.
repeat V-1 times: relax all edges one more round relaxes anything? -> negative cycle -> [-1]