Dijkstra's algorithm and why it fails on negative edges

Video lessonComing soon

1 The fewest roads is not the shortest drive

The graphs lesson gave the city's roads their lengths in km. BFS finds the fewest roads from junction 0, but that is not always the shortest drive. Junction 1 is one road from 0, and that road is 4 km. The drive 0, 2, 1 takes two roads and only 3 km.

4215320123456
The direct road to 1 is 4 km. Through 2 it is 1 + 2 = 3 km

A BFS that adds up the kilometres reaches 1 first by the direct road, marks it, and keeps 4 km. The 3 km drive arrives later, and the mark turns it away.

We need a search that takes junctions in order of kilometres, not roads. That is Dijkstra's algorithm. It finds the shortest drive from one junction, the source, to every other junction, as long as no road has a negative length.

2 Water spreading from junction 0

Picture water poured at junction 0. It flows along every road at 1 km a minute. It reaches junction 2 after 1 minute, and junction 1 after 3 minutes, through 2. The water on the direct road is still a minute away. It reaches 3 after 8 minutes and 4 after 11.

The water reaches the junctions in order of distance, and the minute it first arrives is the shortest drive. Dijkstra's algorithm works out the same order without counting minutes.

It keeps a label dist[v] on every junction: the shortest drive to v found so far. These tentative distances start at 0 for the source and ∞ for the rest. When we finish a junction u, we look at each road from u to a neighbour v, of length w. If going through u beats v's label, the label drops:

dist[v] = min(dist[v], dist[u] + w)

This is relaxing the road. The algorithm repeats one rule: the unfinished junction with the smallest label is final. We finish it and relax its roads.

3 Why the smallest label is final

Let u be the unfinished junction with the smallest label, d. Any route from the source to u starts among the finished junctions, so it must leave them somewhere. Let x be the first unfinished junction on it:

  1. The junction just before x is finished, so its road to x was relaxed. The route up to x is at least dist[x].
  2. dist[x] is at least d, because d is the smallest label.
  3. The rest of the route, from x to u, adds roads of length 0 or more.

So no route to u is shorter than d. In the water picture, water that comes through a farther junction x has to reach x first, so it reaches u too late.

Step 3 is the only place the proof needs a fact about the roads: none is negative. Section 6 shows what happens without it.

4 A min-heap picks the next junction

Reading every label to find the smallest is slow, as section 5 shows. A min-heap from the heaps lesson hands it over in O(log n). Each entry is a pair (distance, vertex). We push a pair whenever a label drops, and pop the smallest pair to choose the next junction.

A heap cannot lower an entry already inside it. So when 1's label drops from 4 to 3, we push (3, 1), and the old (4, 1) stays behind. When it is popped later, 4 is more than dist[1], so we skip it. Such an entry is stale, and skipping it on the way out is lazy deletion. It costs a few extra entries, and we never need to lower one.

In the steps, filled junctions are finished, and the purple one is being taken. Each number is a label, and bold roads gave the labels. The heap lists its entries smallest first, with the popped one crossed and new ones in orange.

Dijkstra from junction 0
421532001∞2∞3∞4∞5∞6∞
(0, 0)
Start: dist[0] = 0, push (0, 0)

The same run as a table, with dist for junctions 0 to 4:

PoppedStale?Labels that dropdist after
(0, 0)no1 to 4, 2 to 10, 4, 1, ∞, ∞
(1, 2)no1 to 30, 3, 1, ∞, ∞
(3, 1)no3 to 80, 3, 1, 8, ∞
(4, 1)yes, 4 > 3none0, 3, 1, 8, ∞
(8, 3)no4 to 110, 3, 1, 8, 11
(11, 4)nonone0, 3, 1, 8, 11

The junctions were finished in the order 0, 2, 1, 3, 4, the order the water reached them. Junctions 5 and 6, on the island, stay at ∞.

The route. To rebuild a drive, we store parent[v] = u whenever u lowers v's label. These links are the bold roads. From 4 we walk back through 3, 1 and 2 to 0, so the drive is 0, 2, 1, 3, 4.

421532001321384115∞6∞
parent = [-1, 2, 0, 1, 3, -1, -1]: the drive 0, 2, 1, 3, 4

5 The code, and what it costs

The code takes the weighted adjacency list from the representation lesson, where adj[u] holds (neighbour, length) pairs. It returns dist, with -1 for a junction it cannot reach. As in the trace, d and u come from the popped entry, and v and w from each road.

On the city, it returns [0, 3, 1, 8, 11, -1, -1].

C++

greater makes it a min-heap. priority_queue puts the largest on top by default. Without the third type, it hands out the farthest label first.

Compare with Long.compare. PriorityQueue is a min-heap, but a long[] has no order of its own. A comparator written as (int) (a[0] - b[0]) overflows once distances pass 2 × 10⁹ and gives the wrong sign.

heapq is a min-heap, and tuples compare item by item, so the smallest distance comes out first. math.inf is larger than any int, so it works as ∞.

No built-in heap, so the tab carries PairHeap. Numbers stay exact up to about 9 × 10¹⁵, so a distance of 10¹⁴ is safe, and Infinity works as ∞.

Less with < makes a min-heap. Call heap.Push and heap.Pop from container/heap, not the type's own methods. int is 64 bits on today's machines, so it holds any distance.

BinaryHeap is a max-heap. Reverse around each pair flips it. The lengths are i64, so d + w adds two 64-bit numbers.

The priority sits beside the element. PriorityQueue<int, long> hands out the vertex with the smallest priority. TryDequeue gives both, and returns false when the heap is empty.

Cost. A label drops only when a junction is finished and relaxes its roads, so the heap gets at most one entry per pair in adj: O(E) entries. Each push and pop costs O(log E), which is O(log V), because E is at most V². Each junction's roads are read once. So Dijkstra with a heap takes O((V + E) log V) time and O(V + E) space.

Without a heap. Dijkstra also works with no heap at all. Each round finds the smallest label by reading every one:

repeat V times:
    u = the unfinished junction with the smallest label
    if dist[u] is ∞: stop
    finish u and relax its roads

Each round reads V labels, so this is O(V²), plus O(E) for the roads. Neither one always wins:

GraphHeapPlain scan
Sparse: V = 10⁵, E = 2 × 10⁵about 5 × 10⁶ steps10¹⁰ steps: TLE
Dense: V = 1,000, every pair joinedabout 10⁷ stepsabout 10⁶ steps

Most problems give sparse graphs, so the heap is the default. For a dense graph given as a matrix, the scan does less work.

6 Why a negative road breaks it

A negative weight is not a length any more. It can be a cost with a refund, such as a toll road that pays back 4 rupees. Here is a small graph of one-way roads with one of them:

Dijkstra on a graph with a road of −4
25−41001∞2∞3∞
Start: dist[0] = 0

Junctions 1 and 3 were already final when the road from 2 came up:

JunctionDijkstra saysShortest drive
12, by 0 → 11, by 0 → 2 → 1
33, by 0 → 1 → 32, by 0 → 2 → 1 → 3

The proof broke at step 3: the rest of a route adds 0 or more. Here x is 2, and the rest is the road 2 → 1, which adds −4. A route through a farther junction came out shorter.

Code that trusts the rule, with a done array that skips finished junctions, returns [0, 1, 5, 3]. Our code's stale check lets (1, 1) through, so it finishes 1 again, fixes 3, and returns [0, 1, 5, 2]. But junctions can now come out of the heap again and again, far past O((V + E) log V). If a cycle of roads adds up to less than 0, the labels drop forever and the loop never ends.

The next lesson, Bellman-Ford, handles negative roads and spots such a cycle.

7 Variants the problems use

The loop stays the same. What changes is where it starts, when it stops, or what a vertex is:

  • Stop at the target. When the target is popped, its label is final, so we can return it there.
  • Many sources. Push every source at distance 0 before the loop, as in multi-source BFS. Each label becomes the distance to the nearest source.
  • A different path cost. Path With Minimum Effort scores a route by its biggest single step, not the sum. The proof still holds, because a route's score never drops when it takes one more road.
  • A vertex with a state. Cheapest Flights Within K Stops limits the stops. A dearer route that used fewer stops can still win later, so the vertex becomes a pair (city, stops used), and the same loop runs over these pairs.

For the shortest drive between every pair of junctions on a small graph, Floyd-Warshall, two lessons on, is simpler.

8 Mistakes, and when to use it

  • Marking a junction done when it is pushed. This is the BFS habit. Junction 1 is first pushed at 4 km. Marked then, it keeps 4, and the code returns [0, 4, 1, 9, 12, -1, -1]. A label is final only when it is popped.
  • No stale check. The old (4, 1) then reads 1's roads again. Here that changes nothing, but on a big graph the repeated reads add up, and code that counts something per pop counts twice.
  • A max-heap by accident. The farthest label comes out first. On the city, 3 and 4 get 9 and 12 before they are fixed. The answers come out right, but with 8 pops instead of 6, and a big graph gets TLE. The note under the code says which way each library's heap points.
  • 32-bit distances. 10⁵ roads of 10⁹ km make a drive of 10¹⁴ km, far past the 2 × 10⁹ an int holds. Keep dist in 64 bits, and never add a road to ∞. With ∞ as INT_MAX, the sum wraps around to a large negative number, the best label of all. Our code adds only to popped distances, which are never ∞.

The sign is roads with different costs and a question about the cheapest route. The costs pick the tool: BFS when every road costs the same, Dijkstra when costs differ and none is negative, and Bellman-Ford when some are negative.

Before choosing Dijkstra, read the weight constraints. If a weight can be below 0, the smallest label is no longer final.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.