Dijkstra's algorithm with a negative edge

In a graph of 3 one-way edges, one of them negative, Dijkstra gives the distance from S to A as 2 where the shortest path is 1. Drag the weight of B → A:

Dijkstra is off by 1

Below −1 the way through B beats S → A's 2, but Dijkstra has already settled A.

Settling A before B

23−2S0A∞B∞
  1. Every distance starts at ∞ except the source, S: 0.
  2. S is the nearest queued node, so it is settled. Its edges set A to 2 and B to 3.
  3. A is nearest at 2. Settling it declares 2 final.
  4. B is settled at 3. Its edge to A would give 3 − 2 = 1, but A is settled and its edges are never looked at again.
  5. Nothing is queued. Dijkstra reports A = 2.
dist[source] = 0;
while (queue.length) {
  const u = takeNearest(queue);
  settled.add(u);
  for (const [v, w] of edges[u]) {
    if (settled.has(v)) continue;
    if (dist[u] + w < dist[v]) dist[v] = dist[u] + w;
  }
}

Settling a node means declaring its distance final. That holds only if every later path is at least as long, which needs every edge to be zero or more.

Bellman–Ford

Bellman–Ford checks 6 edges where Dijkstra checks 3. It never settles: it relaxes every edge V − 1 times over, so any distance can still drop. That is O(V·E) against Dijkstra's O((V + E) log V), and it reports a negative cycle, where no shortest path exists.

Does adding 2 to every weight fix it?

RightWrong

The weights become 4, 5, 0 and Dijkstra returns S → A, which costs 2 in the original graph, not 1. A path of two edges pays the 2 twice, so the best path changes.

Basis

The graph is made for this page. Both algorithms run in model.ts, which fails if they stop giving 2 and 1, and checks that no two-node graph with weights from −3 to 3 separates them. Complexity: Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed., chapter 22.