download

Dijkstra returns the wrong distance with a negative edge. Fix it

Algorithms~15 minReviewed 3 Dec 2026Free · No sign-in

Question

A billing router sends traffic across gateways A, B, C, and D. One link gives a rebate (-4), so edge weights can be negative.

edgeweight
B -> D1
C -> B-4
A -> C6
A -> B4

The Dijkstra function below returns 5 for the shortest cost from A to D, even though A -> C -> B -> D costs 3. Explain why it fails, replace it with Bellman-Ford, and return None if a negative cycle is reachable from start.

"CODE · PYTHON"
import heapq


def shortest_distances(nodes, edges, start):
    adj = {node: [] for node in nodes}
    for src, dst, weight in edges:
        adj[src].append((dst, weight))
    dist = {node: float("inf") for node in nodes}
    dist[start], settled, heap = 0, set(), [(0, start)]
    while heap:
        cost, node = heapq.heappop(heap)
        if node in settled:
            continue
        settled.add(node)
        for dst, weight in adj[node]:
            if dst not in settled and cost + weight < dist[dst]:
                dist[dst] = cost + weight
                heapq.heappush(heap, (dist[dst], dst))
    return dist


nodes = ["A", "B", "C", "D"]
edges = [("B", "D", 1), ("C", "B", -4), ("A", "C", 6), ("A", "B", 4)]
print(shortest_distances(nodes, edges, "A")["D"])  # 5, should be 3
Show hints (3)
  1. "WHY DIJKSTRA FAILS"

    Trace the pop order: A at 0, B at 4, D at 5, then C at 6. When C pops, why can't C -> B (-4) lower B?

  2. "RELAX ALL EDGES"

    Any simple path across V nodes has at most V - 1 edges. Relax every edge (src, dst, weight) for V - 1 full passes.

  3. "DETECT NEGATIVE CYCLES"

    Run one more pass (pass V). If any reachable edge still lowers dist[dst], a negative cycle is reachable from start, so return None.

Show checked explanation

Dijkstra locks a node's distance the first time it leaves the heap. Here it settles B at 4 and D at 5 before popping C at 6, so it never uses C -> B (-4) to lower B to 2 and D to 3. Bellman-Ford relaxes every edge V - 1 times in O(V * E) time and checks pass V for a reachable negative cycle.

"SOLUTION · PYTHON"
def shortest_distances(nodes, edges, start):
    dist = {node: float("inf") for node in nodes}
    dist[start] = 0
    for step in range(len(nodes)):
        changed = False
        for src, dst, weight in edges:
            if dist[src] + weight < dist[dst]:
                if step == len(nodes) - 1:
                    return None  # reachable negative cycle
                dist[dst] = dist[src] + weight
                changed = True
        if not changed:
            break
    return dist


nodes = ["A", "B", "C", "D"]
edges = [("B", "D", 1), ("C", "B", -4), ("A", "C", 6), ("A", "B", 4)]
print(shortest_distances(nodes, edges, "A"))
print(shortest_distances(nodes, edges + [("D", "C", -1)], "A"))
"OUTPUT"
{'A': 0, 'B': 2, 'C': 6, 'D': 3}
None

Code and edge cases run on CPython 3.12.10; official documentation links checked. Checked by an editor other than the author.

Walkthrough

Dijkstra assumes that adding more edges can never shrink a path's cost. In our graph, that fails right away. After A pops at 0, the heap holds (4, "B") and (6, "C"). Next, B pops at 4, gets added to settled, and pushes (5, "D"). Then D pops at 5. When C finally pops at 6, C -> B (-4) offers cost 2 for B, but B is already settled and ignored.

Bellman-Ford makes no greedy lock-in. It sweeps all edges V - 1 times (3 passes for 4 nodes). Even with edges ordered opposite to A -> C -> B -> D, every pass extends shortest paths by at least one edge:

passABCDupdates
start0infinfinfseed A = 0
1046infA -> C, A -> B
20265B -> D (5), C -> B (2)
30263B -> D drops to 3
40263no change; no negative cycle

Why are V - 1 passes enough? Any simple path over V nodes uses at most V - 1 edges, and pass k finds every optimal path of up to k edges. Notice pass 3 was still needed to carry B = 2 forward to D = 3.

On the V-th pass (step == len(nodes) - 1), any further drop means a path of V edges beat every shorter path, so it repeated a node with a negative total loop. Adding ("D", "C", -1) forms C -> B -> D -> C with weight -4 + 1 - 1 = -4. Pass 4 still lowers D from 3 to 1 via B -> D, and the function returns None.

Time is O(V * E) and space is O(V). Breaking early when changed is false saves passes on graphs that settle quickly.

Common mistakes

  • Dropping settled from Dijkstra so popped nodes can re-enter the heap. That fixes this 4-node graph, but negative edges can trigger exponential re-queues and negative cycles loop forever.
  • Looping only V - 2 times. With edges listed in reverse order, pass 2 leaves D at 5 and misses the 3-edge path A -> C -> B -> D costing 3.
  • Omitting the V-th pass. Without that extra sweep, a reachable negative cycle silently returns bogus finite numbers instead of None.
  • Flagging an unreachable negative cycle as an error from start. Because float("inf") + weight < float("inf") is false for finite weights, unreachable cycles stay at inf and do not trigger a false alarm.

Follow-up questions

  • "How do you mark only the nodes affected by a negative cycle instead of returning None?" After V - 1 passes, run V more passes (one pass to catch each reachable negative cycle, plus V - 1 to propagate -inf). Whenever an edge relaxes or starts at -inf, set dist[dst] = float("-inf"), or run BFS from every node relaxed on pass V. On our cycle graph, B, C, and D become -inf while A stays 0.
  • "What if the graph has negative edges but no cycles (a DAG)?" Topologically sort the nodes first, then relax outgoing edges in topological order. Each edge is relaxed once, cutting time from O(V * E) down to O(V + E).
  • "Can you run Bellman-Ford on an undirected graph with a negative edge?" No. An undirected edge of weight -2 between X and Y acts as two directed edges X -> Y (-2) and Y -> X (-2). As soon as X or Y is reachable, walking back and forth forms a -4 negative cycle.

What a strong answer covers

Pinpoints why Dijkstra settles B and D too early and why V - 1 edge passes cover every simple path. Uses pass V to detect reachable negative cycles, and contrasts O(V * E) with Dijkstra's O((V + E) log V).

Open in interactive practice deck →

Original OfferVibe question. NIST DADS: Bellman-Ford algorithm · SciPy bellman_ford · Python heapq.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.