1. Home
  2. Explore
  3. Computer Science
  4. Shortest-Path Algorithms

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Shortest-Path Algorithms

How Shortest-Path Algorithms Find Routes So Quickly

A road map can be represented as a network of nodes and edges. Nodes represent places such as intersections, while edges represent connections such as roads. Finding a route means finding a sequence of edges that connects a starting node to a destination.

The challenge is deciding which route is best. If every road were considered equal, the fewest turns or road segments might be enough. Real roads, however, differ in length and travel time. A useful route-finding method must account for those differences without checking every possible route.

From impossible search to a graph

A large road network can contain tens of millions of intersections. The number of possible routes through such a network grows enormously: a simplified estimate for North America gives about 1022010^{220}10220 possibilities. Checking every route—even at a billion routes per second—would take vastly longer than human history.

The key is not to examine every possible route. It is to use the structure of the network to rule out routes that cannot be best.

A network is often described as a graph:

  • A node represents a location.
  • An edge connects two locations.
  • An edge’s weight represents something to minimize, such as distance or travel time.

A route’s total weight is the sum of the weights of its edges. The shortest path is the route whose total weight is smallest. “Shortest” can mean least distance, least time, or another chosen cost; the algorithm must use weights that match the goal.

Think About It

If two routes each use five roads, but one route covers much more distance, what information is missing from a method that counts only the number of roads?

Breadth-first search: when every step costs the same

Breadth-first search, or BFS, begins at the starting node and explores outward in layers. It first checks every node one edge away, then every node two edges away, then every node three edges away, continuing until it reaches the destination.

Because BFS examines paths in order of their number of edges, it finds a route with the fewest edges when every edge has the same cost. For example, if the destination can be reached in four edges, BFS finds it while checking the four-edge layer; it does not need to inspect longer paths first.

The limitation is that real roads do not all have equal length or travel time. A route with fewer roads may be much longer than one with more roads. BFS does not account for that, so it cannot generally find the lowest-cost route in a weighted road network.

Dijkstra’s algorithm: explore by accumulated cost

Dijkstra’s algorithm extends the basic idea of exploring outward, but it orders the search by total cost rather than by number of edges.

At the beginning, the starting node has cost 000, because no travel is needed to reach it. Every other node is initially assigned a cost of infinity, meaning that no route to it has yet been found. As the algorithm discovers routes, it records the best known cost from the start to each node.

For each edge from a currently explored node to a neighbor, the algorithm asks whether traveling through the current node gives the neighbor a lower cost than its best known cost. If it does, the neighbor’s cost is updated. This step is called relaxing an edge.

For instance, suppose a node can be reached by a newly discovered route costing 666, while its current best known cost is 777. The algorithm updates the node’s cost to 666. If the new route costs 888, the existing cost of 777 remains.

Dijkstra always chooses the unexplored node with the lowest known cost and explores it next. That ordering is what makes the method reliable. Once the lowest-cost unexplored node is selected, no not-yet-explored route can reach it with a lower total cost: any such route would have to pass through a node whose cost is at least as large.

The algorithm can reach the destination before it is safe to stop. A first-discovered route may later be improved, because another route might reach the destination at lower cost. Dijkstra can stop when the destination itself is selected as the lowest-cost unexplored node. At that point, its recorded cost is guaranteed to be optimal.

Dijkstra’s algorithm finds the shortest paths by expanding outward from the start in order of increasing accumulated cost.

Why the method guarantees the shortest path

Suppose the destination’s best known cost is 191919, but an unexplored node has a cost of 161616. That node might lead to a route to the destination costing less than 191919, so the search cannot safely stop yet.

Once the destination is the lowest-cost unexplored node, every other unexplored node has an equal or greater cost. A path to the destination through one of those nodes would have to cost at least as much as reaching that node, and then add the cost of at least one more edge. It therefore cannot produce a better route than the destination’s settled cost.

This is related to BFS’s layer-by-layer guarantee. BFS examines paths by number of edges; Dijkstra examines paths by total weight.

The method works well on modest graphs, but a large map creates a problem: Dijkstra explores in every direction, including directions that lead away from the destination. On a North American road network, a long query may require exploring much of the network.

A-star: use a clue about the destination

A-star, often written A*, improves the search by using an estimate of how far each node is from the destination. It combines two values:

  • The known cost so far, from the start to the current node.
  • A heuristic, an estimate of the remaining cost from the current node to the destination.

A* prioritizes nodes according to the sum of these values. For a distance-based route, the straight-line distance to the destination is a useful estimate. A node that is both inexpensive to reach and geographically closer to the destination will usually be explored earlier than a node that is expensive to reach or lies in the wrong direction.

This creates an intuitive effect: rather than spreading outward equally in every direction, the search tends to head toward the destination. In a city example, A* may explore thousands of nodes where Dijkstra would explore tens of thousands.

The heuristic can be thought of as a penalty for moving away from the goal. A stronger penalty makes the search more focused, while a weaker penalty allows it to spread farther. The estimate must be chosen carefully: if it overestimates the remaining cost, it can mislead the search and undermine the guarantee of finding the true shortest route. A straight-line distance is a lower bound on road distance because a road route cannot be shorter than the direct line between its endpoints.

A* is useful in many navigation tasks beyond driving. Video-game characters and robots can use it to find routes through mazes or around obstacles. Additional costs can discourage travel through dangerous areas, just as road-based costs can represent distance or time.

Distance and travel time are different goals

For the fastest route, distance alone is not the right measure. A longer highway trip can take less time than a shorter trip on slow roads. A possible time-based heuristic is the straight-line distance divided by the maximum allowed speed:

estimated time=straight-line distancemaximum speed\text{estimated time} = \frac{\text{straight-line distance}}{\text{maximum speed}}estimated time=maximum speedstraight-line distance​

This estimate is optimistic: it assumes travel could happen at the maximum speed along a direct route. But it may be a poor guide to actual driving time, because roads curve, speeds vary, and the estimate may be much smaller than the true travel time. It also takes computation to evaluate. For that reason, A* can be very effective for minimizing geographic distance yet offer little advantage over a well-tuned Dijkstra search when the goal is minimizing travel time.

Think About It

Why might a straight-line estimate help when choosing a route by distance but be less informative when choosing a route by driving time?

Bidirectional search: start from both ends

Instead of searching only outward from the starting point, a bidirectional search runs two searches at once: one from the start and one from the destination. The searches stop when their explored regions meet, and the route is formed by joining the two parts.

The benefit comes from how search areas grow. In a simplified map, a one-directional search may cover a large region around the start before reaching a distant destination. Two searches can each cover roughly half the distance, so their explored regions may be much smaller. In a particular city example, bidirectional Dijkstra explored a little over 2,6002{,}6002,600 nodes, compared with more than 7,2007{,}2007,200 for a one-directional search.

Bidirectional search helps, but it does not by itself understand that some roads are more useful than others. A search may still examine a tiny local road even when a major highway is the more sensible route to investigate first.

Road networks have a hierarchy

People often plan long trips in stages: travel along local streets to a major road, use a highway for the long middle section, then leave the highway and return to local streets near the destination. Road networks therefore have a hierarchy. Major highways connect broad regions; local roads connect nearby places.

A basic shortest-path algorithm does not automatically recognize that hierarchy. It considers roads according to their costs, not according to their role in the network. That can leave it exploring many local streets even when the likely route will use major roads.

Early navigation systems addressed this by assigning road classes, such as highways, major local roads, and narrow local roads. A search could look through local roads in a limited area, then move up to a broader class if needed. This reduced the work, but it relied on manually assigned categories and on choosing an adequate search area. If the area was too small, a genuinely better route could be missed; if it was too large, the method could approach the cost of ordinary Dijkstra search.

A more systematic approach is to construct a hierarchy automatically and use it in a way that still guarantees an optimal route.

Nested dissection: ranking important locations

One way to build a hierarchy is nested dissection. Its central idea is to find small groups of nodes that separate a graph into large regions.

Imagine two towns connected by a bridge. If nearly every trip between the towns must pass through one intersection at the bridge, that intersection is important. Removing it separates the network into two parts. A small set of nodes that divides a graph into large regions is called a separator or a cut.

The importance of a separator depends on how much it divides the network. An intersection used only to reach one isolated house is not important to many trips. A bridge between two large regions is much more important. In a continental road network, a small number of crossings over a major barrier may connect vast areas; such bottlenecks should receive high ranks.

Nested dissection repeatedly applies this idea:

  1. Find a small separator that divides the network into large regions.
  2. Give the separator nodes high ranks.
  3. Repeat the process within each separated region.
  4. Continue until every node has a rank.

The result is an ordering from less important nodes to more important ones. The ordering is not required to be perfect. What matters is that it captures the network’s broad structure well enough to make searches efficient.

Think About It

Why could one bridge intersection matter more to a routing system than many ordinary intersections, even if all of them connect roads?

Contraction hierarchies: search upward, but preserve useful routes

A contraction hierarchy uses the node ranking to restrict a query. In a bidirectional search, each search moves upward through the hierarchy, toward more important nodes. Rather than exploring every road in the network, the searches focus on increasingly important connections and can meet near a high-level separator.

There is a danger in this restriction. The shortest route between two important nodes may pass through a lower-ranked node. If the query is only allowed to move upward, it may never consider that route.

The solution is to add shortcuts during preprocessing. A shortcut is a recorded connection between two nodes that represents a path through a node that the later query will not be allowed to visit.

Consider a low-ranked node that connects two higher-ranked nodes. If a shortest route between those higher-ranked neighbors passes through the low-ranked node, the hierarchy adds a shortcut between the higher-ranked nodes. The shortcut’s weight is the cost of the represented route. If a direct edge already exists, the system keeps whichever option has the lower cost.

A path through a low-ranked node is not automatically useful. If the existing higher-level route is already cheaper, no shortcut is needed for that path. Preprocessing therefore adds shortcuts only when they are necessary to preserve a potentially best route.

This explains why a query can safely ignore lower-ranked nodes: the useful effects of paths through those nodes have already been recorded. If a shortcut is eventually selected, the system can expand it back into the real roads it represents.

The shortcut mechanism also makes ranking more flexible. Several different rankings may still produce correct shortest paths because shortcuts can preserve routes that a ranking would otherwise hide. However, a poor ranking can make searches slow or create an excessive number of shortcuts. A good ranking balances two costs:

  • Query cost: how many nodes and edges must be explored.
  • Preprocessing cost: how much work and how many shortcuts are required to build the hierarchy.

For example, contracting a straight line of nodes from one end to the other may require few shortcuts, but a query between the ends may still traverse every node. A different ordering might make the query much faster but require many shortcuts. Efficient systems seek a practical balance.

Customizable contraction hierarchies: separate structure from changing costs

A customizable contraction hierarchy organizes routing into three phases.

1. Build the hierarchy

The network is analyzed, nodes are ranked, and necessary shortcuts are identified. This is the most expensive phase, but it usually needs to be repeated only when the network structure changes—for example, when a road opens or closes.

2. Assign shortcut weights

The cost of a shortcut depends on the costs of the roads it represents. If traffic changes travel-time weights, the shortcut weights can be recalculated without rebuilding the entire structural hierarchy. This makes the approach adaptable to changing traffic conditions.

3. Answer a route query

The system runs a bidirectional search that moves upward through the hierarchy. Because shortcuts preserve relevant routes, this restricted search can still return the true shortest path under the chosen edge weights.

In the described North American network experiment, ordinary Dijkstra search took around seven seconds for a long query and often explored most of the roughly 646464 million nodes. The contraction-hierarchy query took around 200200200 microseconds, explored about 1,4501{,}4501,450 nodes on average, and was about 35,00035{,}00035,000 times faster in that experiment. Such figures depend on the graph and implementation, but they illustrate the advantage of investing in preprocessing to make repeated queries fast.

This kind of trade-off is important for map services. A massive table storing the best route between every pair of locations could make lookups extremely fast, but building and maintaining it would be impractical. At the other extreme, Dijkstra needs almost no preprocessing but can be slow on a huge network. Hierarchical methods aim for the useful middle: substantial speed during queries without requiring an enormous precomputed answer for every possible pair.

How the ideas fit together

These algorithms share a central goal: avoid unnecessary exploration while preserving the guarantee that the returned route is best.

  • BFS explores in order of number of edges and works when all edges have equal cost.
  • Dijkstra’s algorithm explores in order of accumulated cost and handles weighted networks.
  • A* adds a heuristic estimate of the remaining cost, focusing the search toward the destination.
  • Bidirectional search explores from both the start and the destination.
  • Contraction hierarchies use a precomputed ranking and shortcuts to exploit the structure of large road networks.

Modern routing methods can combine these ideas. Their query searches may still use Dijkstra-like cost ordering, while preprocessing, heuristics, or bidirectional search make that core search far more efficient. The general principle is that a simple, reliable foundation can support powerful improvements when the structure of the problem is understood.

Comprehensive review

The shortest-path problem is difficult because the number of possible routes grows too rapidly for exhaustive checking. Graphs make the problem manageable by representing locations as nodes and connections as weighted edges.

BFS finds paths with the fewest edges when every edge has equal cost. For weighted roads, Dijkstra’s algorithm instead records the best known cost to each node and always explores the cheapest unsettled node next. A* uses an estimate of remaining cost to guide the search toward the destination, while bidirectional search reduces the distance each search must cover.

Large road networks also have structure: local roads connect nearby places, while major roads and bottlenecks connect broad regions. Nested dissection identifies important separators and ranks nodes. Contraction hierarchies use those ranks to restrict searches, and shortcuts preserve routes that would otherwise be lost when lower-ranked nodes are skipped. Customizable contraction hierarchies separate the costly construction of the network hierarchy from later updates to road weights and the fast process of answering route queries.

Together, these methods show how shortest-path software can avoid examining nearly all possible routes while still finding a route with the lowest total cost.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent