Bitpath

Lesson 2 · Unit 04

When Dijkstra breaks

Negative edges and Bellman-Ford

11 exercisesabout 3 min

What you practise

  • Negative edges
  • Bellman-Ford's V-1 rounds

Try a question from this lesson

Pick one

An edge can have a negative cost, such as a leg that pays you. Here 0→1 costs 2, 0→2 costs 5 and 2→1 costs −4. What is the cheapest cost from node 0 to node 1?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Bellman-Ford

Bellman-Ford swaps the clever order for patience: relax every edge, then repeat the whole pass, V − 1 passes in all.

After pass k, every shortest path that uses at most k edges is correct, whatever order the edges are listed in and whatever their signs.

INF = float("inf")

def bellman_ford(n, edges):
    dist = [INF] * n
    dist[0] = 0
    for _ in range(n - 1):
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
    return dist
const INF = Infinity;

function bellmanFord(n, edges) {
  const dist = Array(n).fill(INF);
  dist[0] = 0;
  for (let i = 0; i < n - 1; i++) {
    for (const [u, v, w] of edges) {
      if (dist[u] + w < dist[v]) {
        dist[v] = dist[u] + w;
      }
    }
  }
  return dist;
}
const INF = Infinity;

function bellmanFord(
  n: number, edges: number[][],
) {
  const dist = Array<number>(n).fill(INF);
  dist[0] = 0;
  for (let i = 0; i < n - 1; i++) {
    for (const [u, v, w] of edges) {
      if (dist[u] + w < dist[v]) {
        dist[v] = dist[u] + w;
      }
    }
  }
  return dist;
}

Python noteThe loop variable _ is a convention for "the value is not used": only the number of passes matters.

TypeScript noteArray<number>(n) states the item type. A bare Array(n) would be an any[] and switch off type checking for dist.

Concept

One more pass

After V − 1 passes every distance is final, unless some cycle has a negative total. Around such a cycle each lap is cheaper than the last, so there is always something left to improve.

That gives a test: run one extra pass. If any edge can still be relaxed, a negative cycle is reachable.

# dist: the result of the V - 1 passes
def has_negative_cycle(dist, edges):
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            return True
    return False
// dist: the result of the V - 1 passes
function hasNegativeCycle(dist, edges) {
  for (const [u, v, w] of edges) {
    if (dist[u] + w < dist[v]) {
      return true;
    }
  }
  return false;
}
// dist: the result of the V - 1 passes
function hasNegativeCycle(
  dist: number[], edges: number[][],
) {
  for (const [u, v, w] of edges) {
    if (dist[u] + w < dist[v]) {
      return true;
    }
  }
  return false;
}

TypeScript noteedges: number[][] is a list of number lists. const [u, v, w] picks the first three numbers out of each one.

8 more exercises in the app

  • 2× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy