TExcelTAD
Home › Data Structures & Algorithms › Shortest Path Intro

Shortest Path Intro

The shortest path problem asks: what is the cheapest way to get from vertex s to vertex t (or to every vertex) in a graph? "Cheapest" means the smallest sum of edge weights, where a weight might be a distance, a travel time, a price or a network delay. Satellite navigation, network routing (the OSPF protocol), game AI path-finding and flight search all solve shortest path problems constantly.

Unweighted graphs: BFS is enough

If every edge has the same cost, the shortest path is the one with the fewest edges, and breadth-first search finds it (see Graph Traversal). Here BFS spreads out from S, one ring of distance at a time:

python · try it yourself
from collections import deque

graph = {"S": ["A", "B"], "A": ["S", "C"], "B": ["S", "C", "T"], "C": ["A", "B", "T"], "T": ["B", "C"]}

def bfs_distances(graph, start):
    dist = {start: 0}
    queue = deque([start])
    while queue:
        u = queue.popleft()
        for v in sorted(graph[u]):
            if v not in dist:
                dist[v] = dist[u] + 1
                queue.append(v)
    return dist

print(bfs_distances(graph, "S"))
{'S': 0, 'A': 1, 'B': 1, 'C': 2, 'T': 2}

Weighted graphs need more

With weights, the path with fewer edges is not necessarily cheaper. Below, the direct road from S to T costs 10, but going through A and B costs only 1 + 2 + 3 = 6:

python · try it yourself
roads = {("S", "T"): 10, ("S", "A"): 1, ("A", "B"): 2, ("B", "T"): 3}

def cost(path):
    return sum(roads[(a, b)] for a, b in zip(path, path[1:]))

for path in (["S", "T"], ["S", "A", "B", "T"]):
    print(" -> ".join(path), "edges:", len(path) - 1, "cost:", cost(path))
S -> T edges: 1 cost: 10
S -> A -> B -> T edges: 3 cost: 6

The key idea: relaxation

Every shortest path algorithm keeps a table dist[v]: the best distance to v found so far. It starts with dist[s] = 0 and infinity for every other vertex. The basic step is relaxing an edge u → v with weight w:

If dist[u] + w < dist[v], we have found a better way to reach v (through u): set dist[v] = dist[u] + w and remember u as v's predecessor.

python · try it yourself
import math

dist = {"S": 0, "A": math.inf, "B": math.inf, "T": math.inf}
prev = {}

def relax(u, v, w):
    if dist[u] + w < dist[v]:
        print(f"relax {u}->{v}: {dist[u]} + {w} = {dist[u] + w} < {dist[v]}, update")
        dist[v] = dist[u] + w
        prev[v] = u
    else:
        print(f"relax {u}->{v}: {dist[u]} + {w} = {dist[u] + w} is not better than {dist[v]}")

relax("S", "T", 10)
relax("S", "A", 1)
relax("A", "B", 2)
relax("B", "T", 3)
relax("S", "T", 10)          # trying again changes nothing
print(dist, prev)
relax S->T: 0 + 10 = 10 < inf, update
relax S->A: 0 + 1 = 1 < inf, update
relax A->B: 1 + 2 = 3 < inf, update
relax B->T: 3 + 3 = 6 < 10, update
relax S->T: 0 + 10 = 10 is not better than 6
{'S': 0, 'A': 1, 'B': 3, 'T': 6} {'T': 'B', 'A': 'S', 'B': 'A'}

The algorithms differ in which edges they relax, and in what order:

Algorithm Strategy Works with negative weights? Time
BFS unweighted only no weights at all O(V + E)
Dijkstra always expand the closest unfinished vertex no O((V + E) log V) with a heap
Bellman-Ford relax every edge, V - 1 times yes, and detects negative cycles O(V · E)
DAG shortest path relax edges in topological order yes O(V + E)
Floyd-Warshall all pairs, dynamic programming yes O(V³)

Rebuilding the path

The prev table stores, for each vertex, the vertex just before it on the best path. Following it backwards from the target gives the path in reverse:

python · try it yourself
prev = {"A": "S", "B": "A", "T": "B"}

def path_to(prev, target, source="S"):
    path = [target]
    while path[-1] != source:
        path.append(prev[path[-1]])
    return path[::-1]

print(" -> ".join(path_to(prev, "T")))
S -> A -> B -> T

Negative weights and negative cycles

Weights can be negative, for example when an edge is a refund or a profitable currency trade. That breaks Dijkstra's assumption that a vertex, once finished, can't get any closer. Worse, a negative cycle (a loop whose weights sum to less than zero) has no shortest path at all: going round once more always makes the path cheaper. Bellman-Ford can detect this; see its lesson.

Note: Shortest paths have optimal substructure: every part of a shortest path is itself a shortest path. If the best route from S to T goes through B, then its S-to-B part is the best route from S to B. Both Dijkstra and Bellman-Ford rely on this.

Test yourself

Which algorithm finds shortest paths in an unweighted graph?

  1. DFS
  2. BFS
  3. Binary search
  4. Merge sort

dist[u] = 4, dist[v] = 9 and the edge u→v has weight 3. What does relaxing it do?

  1. Nothing
  2. Sets dist[v] to 7
  3. Sets dist[u] to 12
  4. Sets dist[v] to 13

Why is there no shortest path when a reachable negative cycle exists?

  1. The graph becomes disconnected
  2. Each extra lap around the cycle makes the path cheaper
  3. Weights become zero
  4. Paths can't contain cycles