Explore Library
Code QuizAdvanced

Bellman-Ford Relaxation Count

Spot the off-by-one that makes Bellman-Ford under-relax the graph.

Codejavascript
function bellmanFord(edges, V, src) {
  const dist = new Array(V).fill(Infinity);
  dist[src] = 0;
  // relax all edges repeatedly
  for (let i = 0; i < V - 2; i++) {
    for (const [u, v, w] of edges) {
      if (dist[u] + w < dist[v]) {
        dist[v] = dist[u] + w;
      }
    }
  }
  return dist;
}

This Bellman-Ford implementation fails on some graphs. What is the bug?