Algorithm

int[] bellmanFord(int V, List edges, int src) {
  int[] dist = new int[V];
  Arrays.fill(dist, Integer.MAX_VALUE);
  dist[src] = 0;
  for (int i = 0; i < V - 1; i++)
    for (int[] edge : edges) {
      int u = edge[0], v = edge[1], w = edge[2];
      if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v])
        dist[v] = dist[u] + w;
    }
  // Check for negative cycle
  for (int[] edge : edges)
    if (dist[edge[0]] + edge[2] < dist[edge[1]])
      throw new RuntimeException("Negative cycle");
  return dist;
}
Advertisement

Why V-1 rounds

Shortest path has at most V-1 edges. Each round propagates one edge further. After V-1 rounds, all distances final.

Advertisement

Negative cycle detection

Vth round improves a distance → negative cycle exists on path.

Complexity

O(VE). Slow but robust. Only choice when negative edges present.