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

Shortest-Path Algorithms for Road Networks

Modeling routes as a graph

A road network can be represented as a weighted graph:

  • Nodes represent locations such as intersections or cities.

  • Edges represent roads connecting those locations.

  • Edge weights represent the cost of traveling along a road. Depending on the task, cost may mean distance, travel time, or another quantity.

Finding the best route means finding a path from a source node to a destination node that minimizes the total cost of its edges.

The number of possible routes can grow extremely quickly as a network becomes larger. In a road system with tens of millions of intersections, checking every possible route is impractical. Efficient algorithms avoid examining most of those possibilities while still finding an optimal route.


Breadth-First Search

Breadth-First Search (BFS) explores a graph outward from the starting node in layers:

  1. Visit the starting node’s neighbors.

  2. Then visit the neighbors of those nodes that have not already been visited.

  3. Continue outward until reaching the destination.

BFS finds a path with the fewest edges when every edge has equal cost. If the destination is reached after exploring paths of up to five edges, for example, BFS has ruled out any route with fewer edges.

This approach does not necessarily find the shortest route by geographic distance when roads have different lengths. Treating every edge as equal makes a short local road and a long highway count as the same amount of travel. Weighted road networks therefore require a different method.


Dijkstra’s algorithm

Dijkstra’s algorithm finds shortest paths in a graph with nonnegative edge weights. Rather than searching by number of edges, it explores nodes in order of their best-known total cost from the source.

How it works

  1. Assign the source a cost of 000.

  2. Assign every other node an initial cost of infinity, because no route to those nodes has yet been established.

  3. Among all unexplored nodes, select the one with the lowest known cost.

  4. Examine each of its outgoing edges. If traveling through the selected node gives a neighbor a lower cost than its current recorded cost, update that neighbor’s cost and record the route that produced it.

  5. Mark the selected node as explored and repeat.

For an edge from node uuu to node vvv, with weight w(u,v)w(u,v)w(u,v), the candidate cost to vvv through uuu is:

cost(u)+w(u,v)\text{cost}(u) + w(u,v)cost(u)+w(u,v)

If this candidate is less than the currently recorded cost for vvv, the algorithm replaces the old cost with the new one. A node’s cost may be updated several times as better routes are discovered.

Why the algorithm finds optimal paths

Dijkstra always explores the unexplored node with the lowest known cost. With nonnegative edge weights, any route that could improve on that cost would have to pass through a node with an equal or lower cost. Those lower-cost possibilities have already been explored.

Therefore, once a node is selected as the lowest-cost unexplored node, its recorded cost is final: it is the shortest possible path cost from the source to that node.

The same reasoning explains why reaching the destination does not always mean the search should immediately stop. The destination’s first discovered route may not be the cheapest. The algorithm can stop when the destination is selected as the lowest-cost unexplored node, because at that point no unexamined route can improve it.

Strengths and limitations

Dijkstra’s algorithm is general and reliable, but it does not use information about where the destination lies. It expands outward from the source in all directions, potentially exploring large areas that are irrelevant to the desired trip.

For a large road network, a well-tuned Dijkstra search may examine a substantial fraction of the network. In the example discussed, an average query on the North American network took about seven seconds and could involve exploring most of its approximately 64 million nodes. That can be too slow when many people request routes at once.


A* search and heuristic guidance

A modifies Dijkstra’s approach by prioritizing nodes that appear promising for reaching the target. It combines:

  • The known cost from the source to a node.

  • A heuristic estimate of the remaining cost from that node to the destination.

A typical priority value is:

f(n)=g(n)+h(n)f(n) = g(n) + h(n)f(n)=g(n)+h(n)

Here, g(n)g(n)g(n) is the cost of the route already found from the source to node nnn, while h(n)h(n)h(n) estimates the cost from nnn to the target.

For a shortest-distance problem, the straight-line distance from a node to the destination can serve as the heuristic. Nodes that are far from the target receive a larger estimated remaining cost, so A* tends to explore toward the destination instead of spreading evenly in every direction.

The heuristic is a lower-bound estimate: it should not overstate the least possible remaining cost if the algorithm is to preserve the shortest-path guarantee. Straight-line distance is no greater than the actual road distance because roads cannot provide a route shorter than the direct line between two points.

Benefits and trade-offs

On a city-scale example, A* was able to focus its search much more narrowly than ordinary Dijkstra, examining around 7,000 nodes rather than spreading across a much larger region. A* is consequently popular in applications such as maze solving and video-game character navigation. Game versions may include additional penalties for hazards or dangerous areas.

A*’s effectiveness depends on the heuristic:

  • A stronger, accurate heuristic can reduce the search area.

  • A weak heuristic provides little improvement over Dijkstra.

  • A heuristic that overestimates the remaining cost can jeopardize the guarantee of finding the true shortest path.

A* can also be less advantageous when the objective is travel time rather than distance. One possible time heuristic is straight-line distance divided by the maximum allowed speed on the network. This is an optimistic lower bound on travel time, but it may be too loose to guide the search effectively. Computing a heuristic can also add work, including operations such as square roots. In the example described, switching from shortest distance to shortest travel time made A* expand substantially more nodes, while Dijkstra’s search grew only slightly.


Bidirectional search

Bidirectional search runs two searches at once:

  • One begins at the source.

  • The other begins at the destination.

  • The searches progress toward one another until they meet.

Instead of exploring a broad area from one endpoint, each search covers a smaller portion of the route. In a simplified geometric view, if the endpoints are separated by distance RRR, a single search may cover an area roughly proportional to a circle of radius RRR. Two searches meeting around the midpoint each cover a region of roughly half that radius, reducing the total explored area.

The improvement depends on the network, but it can be substantial. In one example, a bidirectional Dijkstra search examined about 2,600 nodes, compared with more than 7,200 for a one-directional search.

Bidirectional search can be combined with other methods, including Dijkstra and hierarchy-based algorithms. It is especially useful when the search can be limited from both ends.


Road networks have a hierarchy

Roads differ in their roles. A person traveling a long distance typically uses local streets near the start, moves onto major roads or highways for much of the journey, and returns to local streets near the destination.

Ordinary Dijkstra and A* do not inherently understand this hierarchy. They may examine a small local road even when a highway is the more relevant route toward a distant destination. Their decisions are based on costs and heuristic estimates, not on the road’s broader function in the network.

Manually assigned road hierarchies

Early navigation approaches used road categories assigned by surveyors or mapping companies. Roads might be classified as narrow local roads, major local roads, or express highways. A routing system could then search lower-level roads first, expand to higher-level roads if necessary, and use searches from both endpoints.

This can reduce the search area, but it creates important difficulties:

  • The hierarchy must be assigned correctly and consistently.

  • A route that appears best within a restricted search area might not be the true shortest route.

  • A candidate area that is too small can exclude the optimal route.

  • Making the area large enough to avoid missed routes can erase much of the speed advantage.

A better method needs to exploit the network’s hierarchy while guaranteeing that it does not omit the shortest path.


Preprocessing: balancing setup cost and query speed

Routing methods can be compared by how much work they perform before a request and how quickly they answer each request.

At one extreme, a system could store the shortest route between every pair of locations. Queries would be extremely fast, but creating and storing the table would be impractical. For tens of millions of intersections, even computing paths from every intersection could take more than a decade on a single core, and the resulting table could require more than eight petabytes. Road closures, new bridges, and traffic changes would also require expensive updates.

At the other extreme, Dijkstra’s algorithm requires no large preprocessing step but may take too long for repeated queries on a large network.

Practical routing methods seek a balance: moderate preprocessing in exchange for very fast queries, with a way to update the data when the graph or its costs change.


Contraction hierarchies

A contraction hierarchy assigns each node a rank that represents its importance in the network. The routing search then moves upward through this hierarchy from both the source and destination. Preprocessing adds shortcuts where necessary so that restricting searches to higher-ranked nodes does not remove the true shortest route.

Ranking nodes with nested dissection

The hierarchy can be constructed using nested dissection, which repeatedly identifies small sets of nodes that divide the graph into large regions.

A small set of nodes that separates one part of a graph from another is called a separator or cut. Separators are important because many routes between regions must pass through them. For example, a bridge may be crucial when it connects two communities, especially if it divides the network into similarly sized sides.

The process works conceptually as follows:

  1. Find a relatively small set of nodes that divides the graph into large regions.

  2. Give those separator nodes high ranks.

  3. Repeat the process within each region.

  4. Continue until the nodes have been ordered from low rank to high rank.

On a continental network, major separators may correspond to important crossings or geographic boundaries. The highest-ranked nodes capture major bottlenecks, while lower-ranked separators divide smaller subregions.

Nested dissection aims to create an ordering that supports both fast searches and a manageable number of shortcuts. The ordering does not have to be perfect, but poor choices can make queries slow or cause the shortcut network to grow excessively.

Upward search

After ranking, a query uses bidirectional Dijkstra but restricts each search to moving upward in rank:

  • The source-side search follows edges toward higher-ranked nodes.

  • The destination-side search does the same from the opposite end.

  • The searches meet in the higher levels of the hierarchy.

This restriction is what reduces the search space. However, it could miss a shortest route that passes through lower-ranked nodes between higher-ranked nodes. Shortcuts preserve those routes.

Adding shortcuts

A shortcut is a stored edge that represents a path through one or more intermediate nodes. It is not necessarily a real road; it records the cost of a route that would otherwise be skipped by the upward-only search.

Shortcuts are added from the lowest-ranked nodes upward:

  1. Consider a low-ranked node that connects two higher-ranked nodes.

  2. Check whether traveling through the low-ranked node could be the shortest connection between those higher-ranked nodes.

  3. If needed, add a shortcut directly between the higher-ranked nodes with the cost of that route.

  4. If a direct edge or another shortcut already provides a cheaper route, retain the minimum-cost option.

This process ensures that paths using lower-ranked nodes remain representable even though query searches do not travel downward through the hierarchy. It allows the search to skip unimportant intermediate nodes without losing the optimal path.

Why ranking quality matters

Many rankings can still produce correct shortest-path results when shortcuts are added appropriately. But different rankings can have very different efficiency.

  • A poor ordering may require many nodes to be explored during a query.

  • Another ordering may require many shortcuts, increasing storage and preprocessing costs.

  • A useful ordering balances the number of shortcuts against how much each query is accelerated.

Nested dissection provides a practical way to obtain a reasonably effective ordering without requiring a perfectly optimized hierarchy.


Customizable contraction hierarchies

A customizable contraction hierarchy separates preprocessing into three phases:

1. Build the hierarchy

The graph is ordered and the necessary shortcut structure is determined. This is the most expensive phase, but it usually changes only when the road network itself changes, such as when a road closes or a bridge opens.

2. Customize shortcut weights

The costs of shortcuts are calculated using the current edge weights. If those weights represent travel times, traffic changes may require this phase to be rerun. It is designed to be much faster than rebuilding the entire hierarchy.

This separation is useful because the road structure and the costs placed on that structure do not change in the same way: the network layout may remain stable while travel times vary.

3. Run the query

The actual route search uses bidirectional, upward-only Dijkstra over the customized hierarchy. Since it examines only a small number of nodes and edges, it can answer queries extremely quickly.

In the North American network example, the query took about 200 microseconds, with some configurations reaching around 100 microseconds. The search examined an average of roughly 1,450 nodes instead of a large fraction of the network, making it tens of thousands of times faster than the ordinary Dijkstra comparison in that experiment.


How the algorithms relate

The algorithms form a progression in how they reduce search effort:

  • BFS searches by number of edges and is suitable when all edges have equal cost.

  • Dijkstra’s algorithm handles weighted edges and guarantees optimal routes, but may explore a large area.

  • A uses a destination-directed heuristic to prioritize promising nodes.

  • Bidirectional search starts from both ends and allows the two search frontiers to meet.

  • Contraction hierarchies use preprocessing and shortcuts to exploit the network’s structure while preserving shortest-path correctness.

The later methods do not discard Dijkstra’s core idea: they still rely on shortest-cost search, but guide or restrict that search using additional information. A contraction hierarchy, for example, uses bidirectional Dijkstra within a carefully prepared graph.


Key principles

A shortest-path algorithm is correct only if its search strategy and stored information preserve every potentially optimal route.

  • A route’s meaning of “shortest” depends on the chosen edge weights: distance and travel time can produce different results.

  • Heuristics can make a search more focused, but their quality determines how much they help.

  • Bidirectional search reduces the area explored by approaching from both endpoints.

  • Road-network hierarchy offers powerful guidance, but manually assigned levels can cause optimal routes to be missed.

  • Preprocessing can greatly accelerate queries, but it has costs in computation, storage, and updating.

  • Shortcuts allow a hierarchy-based search to skip lower-level nodes while still accounting for paths through them.

The central design challenge is to minimize the work done for each route request without sacrificing the guarantee that the returned route is optimal.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent