All topics
97

Cheapest route across a weighted map

Tier 1Locked

Where it runs

1. The problem

A map app has to take you from home to the airport. Some roads are short but full of traffic. Some are long but empty. You want the route that takes the least total time, however many turns it has.

So counting roads does not help here: three fast highway roads can beat two slow city streets. Each road has a weight (a cost, such as minutes, kilometres or delay). You want the smallest total cost to reach each place.

The same task shows up in a network of computers. Each link has a measured delay. You want the smallest total delay from one computer to every other one.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included
Shortest distances with Dijkstra
dijkstra(6, [[[1, 4], [2, 1]], [[3, 1]], [[1, 2], [3, 5]], [[4, 3], [5, 6]], [[5, 1]], []], 0)
number above a node = best known distance from 0
heap as [distance, node], nearest first
front →[0, 0]

Find the shortest distance from node 0 to every node. Every distance starts at ∞, node 0 gets 0 and goes into the heap.

Speed race
Bellman-Ford and Dijkstra on the same weighted graph of 16 nodes

Bars: the current distance from node 0 to each node. A full-height bar means the node is not reached yet.

One operation is one edge check or one step inside the heap. Every frame, each lane does the same number of operations, so the slow one falls behind.

Bellman-Ford O(V·E)
0 operations
Dijkstra with a heap O(E log V)
0 operations

 

And with more numbers

Operations for n numbers, and roughly how long they take at 100 million simple operations a second. An estimate from the same count, not a measurement.

n = 1,000
Bellman-Ford2M · 20 ms
Dijkstra with a heap14K · under 1 ms
n = 100,000
Bellman-Ford20B · 3.3 min
Dijkstra with a heap2.2M · 22 ms
n = 10,000,000
Bellman-Ford200T · 23 days
Dijkstra with a heap299M · 3 s

Recognise it

Dijkstra's algorithm

Say these words and it is this pattern

  • cheapest/shortest path with weighted edges
  • non-negative edge weights
  • minimum total cost to reach every node
  • network delay time / route cost, not fewest roads
  • weighted graph, single-source shortest paths

Looks similar, isn't

V nodes and E edges give O(E log V) with a heap. Negative weights break it, so use Bellman-Ford.

On LeetCode

Problems that ask for the cheapest route when edges have different non-negative costs. Dijkstra pops the closest unfinished node from a min-heap and relaxes its edges.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy