Algo-Sim › Advanced Graphs
Bellman-Ford (negative weights)
Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input
Shortest distances from a source when some edges are negative: relax every edge n − 1 times, then one extra pass detects a negative cycle.
Problem
Given a directed graph with nodes 0..n − 1 whose edge weights may be negative, return the shortest distance from src to every node (∞ where unreachable). If a negative cycle is reachable from src, shortest paths are not defined: return null.
Constraints
- 1 ≤ n ≤ 10³ and 0 ≤ edges ≤ 10⁴ in typical problems
- Weights may be negative
- O(V · E) time
- Dijkstra is wrong once a weight is negative
Edge cases to test
- A negative cycle reachable from the source
- A negative cycle that is not reachable (distances still valid)
- An unreachable node stays ∞
Follow-up questions
- Why n − 1 rounds?
- A shortest path has at most n − 1 edges, and round i fixes every path of i edges: O(V·E).
- How do you speed it up?
- Stop early when a round changes nothing; SPFA relaxes only nodes whose distance changed, often much faster but still O(V·E) worst case.
Solution
Java
public int[] bellmanFord(int n, int[][] edges, int src) {
int[] dist = new int[n];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;
for (int round = 1; round < n; round++) {
boolean changed = false;
for (int[] e : edges) {
int u = e[0], v = e[1], w = e[2];
if (dist[u] == Integer.MAX_VALUE) continue;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
changed = true;
}
}
if (!changed) return dist;
}
// One more pass: anything that still improves is on or after a negative cycle.
for (int[] e : edges) {
if (dist[e[0]] != Integer.MAX_VALUE && dist[e[0]] + e[2] < dist[e[1]]) return null;
}
return dist;
}Python
def bellman_ford(n, edges, src):
dist = [float("inf")] * n
dist[src] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] == float("inf"):
continue
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
return dist
# One more pass: anything that still improves is on or after a negative cycle.
for u, v, w in edges:
if dist[u] + w < dist[v]:
return None
return distC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
optional<vector<int>> bellmanFord(int n, vector<vector<int>> &edges, int src) {
vector<int> dist = vector<int>(n);
fill(dist.begin(), dist.end(), INT_MAX);
dist[src] = 0;
for (int round = 1; round < n; round++) {
bool changed = false;
for (vector<int> &e : edges) {
int u = e[0], v = e[1], w = e[2];
if (dist[u] == INT_MAX)
continue;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
changed = true;
}
}
if (!changed)
return dist;
}
// One more pass: anything that still improves is on or after a negative cycle.
for (vector<int> &e : edges) {
if (dist[e[0]] != INT_MAX && dist[e[0]] + e[2] < dist[e[1]])
return nullopt;
}
return dist;
}
};
More Advanced Graphs problems
- Network Delay Time (Medium)
- Evaluate Division (Medium)
- Course Schedule II (Medium)
- Alien Dictionary (Hard)
- Redundant Connection (Medium)
- Number of Connected Components (Union-Find) (Medium)
- Accounts Merge (Medium)
- Minimum Spanning Tree (Kruskal) (Medium)
- Minimum Spanning Tree (Prim) (Medium)
- Min Cost to Connect All Points (Medium)
- Cheapest Flights Within K Stops (Medium)
- Find the City (Floyd-Warshall) (Medium)
- Critical Connections in a Network (Hard)
- Articulation Points (Cut Vertices) (Hard)
- Strongly Connected Components (Hard)
- Reconstruct Itinerary (Hard)
- Minimum Height Trees (Medium)