Shortest-Path Algorithms


Shortest-Path Algorithms

Corey
Imagine finding the absolute shortest drive from New York to San Francisco. The North American road network has more than 64 million intersections, and a rough estimate puts the number of possible routes around 10 to the 220th power. Even checking a billion routes every second would take more than 10 to the 200 years. Yet a maps app can return a route in just a few seconds. The key is not checking every route—it’s using algorithms that rule out enormous amounts of unnecessary searching.

Maria
And this problem isn’t limited to driving directions. Robots, video-game characters, and other independent systems also need to navigate mazes or obstacle courses. The story of one foundational solution begins with a demonstration for an early computer called ARMAC, and a very practical question: what’s the shortest way to travel between two towns?

Corey
That question came to Edsger Dijkstra in 1956, while he was working at the Mathematical Center in the Netherlands. Computers were so unfamiliar that, when he listed his profession as programmer on his marriage paperwork, officials wouldn’t accept it. He was looking for a demonstration that ordinary people could understand—and could understand the answer to.

Maria
His example was a trip from Rotterdam to Groningen. We can represent a road map as a graph: cities or intersections are nodes, and roads connecting them are edges. One basic approach is breadth-first search. Starting at Rotterdam, explore its neighboring nodes, then the neighbors of those nodes, and keep expanding outward until Groningen appears.

Corey
Breadth-first search finds a path with the fewest edges because it checks every node one step away before checking two steps away, then three, and so on. If the destination is first reached after five steps, there can’t be a route with fewer steps that it somehow skipped. But that guarantee assumes every edge counts as the same length.

Maria
And roads plainly aren’t all the same length. If we put distances—or other costs—on the edges, the route with the fewest roads might not be the shortest route. Dijkstra’s insight was to keep track of the best known total cost from the starting point to every node, and explore the graph in order of those costs.

Corey
At the start, the source node has cost zero, and every other node has cost infinity because no route to them has been found yet. From the source, examine each neighboring road and update a neighbor’s cost whenever the route just found is cheaper than its current recorded cost. Then mark the source explored.

Maria
Next, choose the unexplored node with the lowest known cost. Examine its outgoing roads and see whether going through that node improves the recorded costs of its neighbors. If a node already has a cheaper route, leave its cost alone. A node’s cost can be updated more than once as better routes are discovered.

Corey
For example, perhaps a node is first reached by a route costing seven, and later a different route brings that total down to six. Dijkstra updates it to six. The crucial rule is that the algorithm always explores the currently cheapest unexplored node—not simply the nearest node in number of steps.

Maria
That rule explains why it can stop with confidence. Suppose Groningen has been reached at cost 19, but another unexplored node has cost 16. That node could still lead to a route to Groningen cheaper than 19, so the search continues. If Groningen becomes the lowest-cost unexplored node, then every route with a lower cost has already been considered, and none reached it. The route is shortest.

Corey
So Dijkstra’s algorithm generalizes the idea behind breadth-first search. Breadth-first search expands by number of edges; Dijkstra expands by increasing total cost. Dijkstra came up with the idea during a coffee break while shopping in Amsterdam, and later described it as a 20-minute invention designed without pencil and paper.

Maria
He used it to demonstrate ARMAC at its 1956 inauguration: audience members named two towns, and the computer printed the shortest route town by town. Dijkstra’s paper was published in 1959 in a new German mathematics journal. The algorithm later became famous, even though Dijkstra himself was surprised to discover a method named after him.

Corey
But a great shortest-path algorithm isn’t automatically fast enough for a global maps service. In a New York City example—from Newark Airport to the Central Park Zoo—Dijkstra examines routes in increasing distance and searches more than 65,000 nodes, including places well off in the wrong direction. It can still run in about a tenth of a second, but the search spreads out broadly.

Maria
On the North American network, a well-tuned Dijkstra search takes around seven seconds per path on average in the described test, and many searches explore most of the 64 million nodes. That average uses randomly selected point pairs, so it includes many long journeys. A single seven-second query sounds manageable, until millions of people are asking for directions at once.

Corey
That’s why the goal is much more demanding than just making one route feel quick. To serve many users, a search may need to take less than a millisecond—about 7,000 times faster than that seven-second Dijkstra benchmark. One way to reduce the search is to use a clue about where the destination is.

Maria
That clue leads to A-star. For each node, combine the known cost from the source with a heuristic estimate of how far the node is from the target. Straight-line distance, calculated from latitude and longitude, can serve as that estimate. Nodes that are both cheap to reach and appear closer to the destination get priority.

Corey
A useful picture is to imagine each node’s straight-line distance to the target as its height. Nodes farther from the target sit higher, and A-star’s heuristic penalizes moves in the wrong direction. Instead of spreading outward in every direction like Dijkstra, it tends to head toward the destination.

Maria
On the Newark-to-zoo example, A-star checks around 7,000 nodes—nearly ten times fewer than Dijkstra. The heuristic’s strength can be adjusted: a steeper penalty makes the search spread less. A-star is popular for maze solving and video-game characters, including Minecraft mobs that use a version with extra penalties for dangerous areas.

Corey
There’s an important qualification: A-star can be much more focused, but the heuristic has to be chosen for the objective. At worst, A-star may check as many nodes as Dijkstra. And if we care about fastest travel time rather than shortest geographic distance, a natural heuristic is straight-line distance divided by the maximum allowed speed. That gives a lower bound on travel time, but it can be a very rough estimate.

Maria
In the example described, A-star explores about 9.5 times fewer nodes than Dijkstra for shortest distance. Switch the objective to travel time, though, and A-star’s node count triples, while Dijkstra’s increases by only about 10 percent. Evaluating the heuristic also adds work, including a square-root computation. So for travel time, A-star can lose to a well-tuned Dijkstra.

Corey
Another improvement is to search from both ends. Run one Dijkstra search from the starting point and another from the destination, and stop when the frontiers meet. If the points are about distance R apart, a single search covers roughly a circle of area pi R squared. Two searches meet around halfway and, in the simplified picture, cover about half that area.

Maria
In one example from Carnegie Hall to Wall Street, ordinary Dijkstra explored more than 7,200 nodes, while bidirectional Dijkstra explored a little over 2,600. That’s close to a threefold improvement. Still, even two-sided search doesn’t understand the structure people naturally use when they drive.

Corey
A person often takes local streets to reach a highway, travels on the highway for a while, then returns to local streets near the destination. Basic Dijkstra and A-star don’t inherently know that road hierarchy. They can be tempted to examine a twisty local road just because its cost looks promising, even when a major road is the sensible way to make progress.

Maria
Early in-car GPS systems addressed that with manually assigned road classes. Surveyors recorded details such as speed limits and road width, and mapping companies categorized roads into levels—for example, express highways, major local roads, and narrow roads. A bidirectional search could first examine narrow roads in a candidate area, then expand to a higher road class if it didn’t find the destination.

Corey
The catch is choosing the hierarchy and candidate areas correctly. If an area is too small, the algorithm might return a highway route even though a better route using local roads exists. If the area is made very large to avoid missing the true shortest route, the search starts to lose its advantage. A world-scale routing system needs a more systematic way to use hierarchy while guaranteeing the answer.

Maria
This brings us to a central trade-off: spend time preparing the graph so that individual route queries are fast, but don’t spend too much time preparing it or store too much information. A table containing the shortest route between every pair of intersections would make lookups quick, but building it for 64 million intersections would take more than a decade of compute on one core, and the raw table would exceed eight petabytes.

Corey
That huge table would also need rebuilding when roads close, bridges open, or traffic changes. At the opposite extreme, ordinary Dijkstra needs no preprocessing, but queries can be slow. The useful region lies between those extremes: manageable preprocessing and very fast searches. Contraction hierarchies aim to reach that balance.

Maria
The first step is to assign importance ranks to nodes. The basic intuition is that some intersections are bottlenecks for many routes. Imagine two towns connected by a bridge, with one house across it. For someone going to that house, the bridge intersection is essential, but it matters less to the rest of the town.

Corey
As more houses are built on the far side, that bridge becomes important for more trips. It matters especially when the bridge divides the area into two roughly equal parts, because many routes between the sides must pass through it. A small set of nodes that splits a graph into large pieces is called a small cut, and its nodes can be important.

Maria
Across North America, one prominent cut consists of 102 nodes that roughly separate the east and west. Routes between the two sides have to cross one of those nodes, with many of the crossings associated with the Mississippi River. The algorithm ranks those bottlenecks highly, then looks for further cuts within each side, and keeps repeating the process.

Corey
That recursive way of dividing and ranking the graph is called nested dissection. It produces an ordering from the most important nodes down to the least important ones. The ordering should help searches stay small, but it must also support a guarantee that no shorter route gets overlooked.

Maria
Once the ranks are assigned, picture pulling the nodes down in order, with low-ranked nodes at the bottom and important ones higher up. A query runs bidirectional Dijkstra, but each search is restricted to moving upward in rank. The two searches can meet higher in the hierarchy instead of exploring every road between the endpoints.

Corey
That restriction creates a problem: a shortest route might go through a low-ranked node that the upward-only search is not allowed to visit. The fix is preprocessing with shortcuts. Start at a low-ranked node and check whether it connects two higher-ranked nodes. If so, add a shortcut between those higher nodes whose weight represents the route through the low node.

Maria
For example, if node one connects to nodes three and eight, a route from three through one to eight may be the shortest way between three and eight. Add an edge representing that combined route, so a later upward search can use it without visiting node one. The shortcut isn’t a real road; it records the cost and path of a route through lower-ranked nodes.

Corey
As preprocessing continues upward through the ranks, there may be several possible lower-node routes between a pair, or an edge may already exist. The shortcut should represent the minimum-cost option. This preserves useful paths while allowing the query to ignore low-ranked nodes when it searches.

Maria
Shortcuts also make the precise ranking less fragile. A ranking that fails to preserve a shortest route directly can have that route represented by a shortcut later. So multiple rankings can still give correct answers. But they aren’t equally efficient: one ordering might require many shortcuts or leave the query exploring many edges.

Corey
That’s the trade-off in choosing an ordering: fewer shortcuts versus faster queries. If nodes in a straight line are contracted from one end to the other, you might need no shortcuts, but a search from end to end still has to inspect the whole line. Another ordering can reduce the query to just a couple of edges, but may require many shortcuts.

Maria
In practice, nested dissection gives a useful ordering without taking too long. The resulting method is called a customizable contraction hierarchy. Its first phase orders the nodes and builds the shortcuts. That’s the most expensive phase, but it need not be repeated unless the graph changes—for example, because of a new bridge or a road closure.

Corey
The second phase calculates the weights of the shortcuts. When traffic updates alter the relevant weights, this phase has to be run again, so it needs to be relatively quick. In the described experiment, it took around seven or eight seconds without parallelization, and about a second with it.

Maria
Then comes the actual route query. On the North American network, the reported contraction-hierarchy query took around 200 microseconds, with configurations reaching about 100 microseconds. It explored an average of roughly 1,450 nodes—about 44,000 times fewer than Dijkstra in terms of search space, and around 35,000 times faster in that experiment.

Corey
For a route from San Francisco to Montreal, Dijkstra would examine nodes across a huge region. The contraction hierarchy instead focuses on about 1,236 nodes, concentrated near the start and destination. Once each search climbs far enough up the hierarchy, it only needs to consider important cuts, such as the Mississippi crossings.

Maria
We don’t know from this account exactly what Google Maps, Apple Maps, or other major routing services use internally. Contraction hierarchies could be used to build such systems, and they are one of several routing approaches. The larger point is that fast modern routing can still build on Dijkstra’s core idea, combined with preprocessing that exploits the structure of the road network.

Corey
Dijkstra’s algorithm has remained influential for decades. The source notes that many later shortest-path algorithms, including variations on contraction hierarchies and a more recent theoretical breakthrough, still use pieces of his approach. One reason is its simplicity. Dijkstra said, “Simplicity is prerequisite for reliability.”

Maria
And there’s a human lesson in that, too. Dijkstra thought carefully about a problem before reaching for a pen, and he believed programmers—not machines—were accountable for their work. His hope was that people might someday pause over a quick, messy solution and ask, “Would Dijkstra have liked this?” Making even our own small corner of the world thoughtful and elegant can be a legacy worth leaving.

Ask anything
We've read this whole study set, so questions about it get the best answers.