Sub topic 2
The Single-Source Shortest Path Problem
This chapter pins down what "shortest path" means before any algorithm appears. It assumes you know basic graph terms (vertex, edge, directed and undirected graphs), the adjacency list representation from the previous chapter, Big-O notation, basic Python, and breadth-first search (BFS). A precise problem statement matters because each later chapter relies on it. The correctness proof, the failure on negative weights and the early-termination trick all depend on exactly what the algorithm promises to compute.
Paths, Path Weights, and Distance
A weighted directed graph is a set of vertices V, a set of edges E, and a weight function w that assigns a number w(u, v) to each edge (u, v).
A path from u to v is a sequence of vertices v0, v1, ..., vk with v0 = u and vk = v, where every consecutive pair (vi, vi+1) is an edge. The path has k edges. A path with zero edges, the single vertex u, is a valid path from u to itself.
The weight of a path is the sum of its edge weights:
- weight(v0, ..., vk) = w(v0, v1) + w(v1, v2) + ... + w(vk-1, vk)
The shortest-path distance from s to v, written δ(s, v), is the minimum weight over all paths from s to v. If no such path exists, δ(s, v) = ∞.
A shortest path is any path whose weight equals δ(s, v). Keep the distance and the path apart in your head. The distance is a single number, and it is unique. A shortest path is a route, and several different routes can tie for the minimum.
The Problem Statement
The single-source shortest path problem (SSSP) is:
- Input: a weighted directed graph G = (V, E, w) and a source vertex s.
- Output: δ(s, v) for every vertex v in V, and usually one shortest path to each reachable v.
Dijkstra's algorithm solves SSSP under one extra condition: every edge weight is non-negative, w(u, v) ≥ 0. That condition is part of the problem the algorithm solves. It is not a minor detail of the implementation.
The output normally comes as two maps:
| Output | Type | Meaning |
|---|---|---|
| `dist` | vertex → number | `dist[v]` = δ(s, v), or ∞ / absent if unreachable |
| `prev` | vertex → vertex | `prev[v]` = the vertex just before v on one chosen shortest path |
The prev map is enough to rebuild every path, which a later chapter covers. You don't store each path in full. That could cost O(V²) space, while prev costs O(V).
The Four Problem Variants
Shortest-path questions come in four standard forms:
| Variant | Question | Typical approach |
|---|---|---|
| Single-pair | Shortest path from s to t | Run SSSP from s, possibly stopping early |
| Single-source | Shortest paths from s to all v | Dijkstra, Bellman-Ford |
| Single-destination | Shortest paths from all v to t | Reverse every edge, then SSSP from t |
| All-pairs | Shortest paths between every pair | Repeated SSSP, or Floyd-Warshall |
You might expect single-pair to be easier than single-source. In the worst case it isn't: no known algorithm solves single-pair asymptotically faster than single-source on general graphs. To be sure no cheaper route to t exists, you may have to look at most of the graph anyway. For this reason Dijkstra's algorithm is framed as a single-source algorithm, and the single-pair speed-up of stopping early comes later as an optimization.
A Worked Example
Take s = S and list the paths to each vertex:
| Target | Candidate paths (weight) | δ(S, v) |
|---|---|---|
| S | S (0) | 0 |
| A | S→A (2) | 2 |
| B | S→B (5), S→A→B (3) | 3 |
| C | S→A→C (6), S→B→C (6), S→A→B→C (4) | 4 |
| E | none | ∞ |
Several points from this table come up again in later chapters:
- The fewest edges is not the lowest weight. The path S→A→B→C has three edges but weighs less than either two-edge route. BFS, which counts edges, would pick a two-edge path and get the wrong answer.
- Edge direction matters. E has an edge into S, but no edge goes from S to E, so E is unreachable from S.
- Distances reuse each other. δ(S, C) = δ(S, B) + w(B, C) = 3 + 1. The best route to C extends the best route to B.
Structural Properties You Will Rely On
Dijkstra's algorithm works because of two properties of shortest paths.
Optimal Substructure
Any subpath of a shortest path is itself a shortest path. If S→A→B→C is shortest from S to C, then S→A→B must be shortest from S to B. Suppose some cheaper route to B existed. You could swap it in and get a cheaper route to C, which contradicts the claim that S→A→B→C was shortest.
This property means one predecessor per vertex is enough. The shortest paths from s fit together into a shortest-path tree rooted at s. In the example, the tree edges are S→A, A→B and B→C.
The Triangle Inequality
For every edge (u, v): δ(s, v) ≤ δ(s, u) + w(u, v). Going to u by the best route and then taking the edge to v is one way to reach v, so the best way can't cost more than that. The next chapter turns this inequality into an operation called relaxation.
Edge Cases and Conventions
Real graphs have quirks the textbook definition ignores. Decide how to handle each one up front:
| Situation | Convention |
|---|---|
| Unreachable vertex | δ = ∞; either store `math.inf` or leave the key out of `dist` |
| Source itself | δ(s, s) = 0 when weights are non-negative |
| Zero-weight edges | Allowed; Dijkstra handles them correctly |
| Ties | Distance is unique; `prev` records one of the tied paths, chosen arbitrarily |
| Parallel edges u→v | Only the cheapest one can matter |
| Self-loops | Never useful when weights are non-negative |
| Undirected graph | Store each edge {u, v} as both (u, v) and (v, u) |
| Negative edge weights | Dijkstra may return wrong answers; covered in a later chapter |
| Negative-weight cycle reachable from s | δ is undefined (−∞) for vertices beyond it |
A Brute-Force Reference Solver
Before writing a fast algorithm, it helps to have a slow one you trust as a test oracle. With non-negative weights, some shortest path to each reachable vertex is simple, meaning it repeats no vertex. A cycle has weight ≥ 0, so removing it never makes a path longer. That means it is enough to enumerate every simple path from s:
import math
def all_vertices(graph):
"""Collect vertices that appear as keys or as neighbors."""
vertices = list(graph)
seen = set(vertices)
for u in graph:
for v, _ in graph[u]:
if v not in seen:
seen.add(v)
vertices.append(v)
return vertices
def brute_force_distances(graph, source):
"""Exact SSSP by enumerating simple paths. Exponential time; tests only.
Assumes all weights are non-negative."""
best = {v: math.inf for v in all_vertices(graph)}
best[source] = 0
def explore(u, cost, on_path):
for v, w in graph.get(u, []):
if v in on_path:
continue # keep paths simple
new_cost = cost + w
if new_cost < best[v]:
best[v] = new_cost
on_path.add(v)
explore(v, new_cost, on_path)
on_path.remove(v)
explore(source, 0, {source})
return best
graph = {
"S": [("A", 2), ("B", 5)],
"A": [("B", 1), ("C", 4)],
"B": [("C", 1)],
"C": [],
"E": [("S", 1)],
}
print(brute_force_distances(graph, "S"))
# {'S': 0, 'A': 2, 'B': 3, 'C': 4, 'E': inf}The output matches the table. This solver runs in exponential time, because a dense graph has exponentially many simple paths. Even so, it is useful. Once you write Dijkstra's algorithm, compare its output to brute_force_distances on hundreds of small random graphs. Any mismatch points to a bug.
Common Errors When Stating the Problem
- Mixing up hop count and weight. Using BFS on a weighted graph returns paths with the fewest edges, which is generally not the lowest-weight path.
- Forgetting direction. Treating a one-way edge as two-way changes the answers, and adding reverse edges by mistake can create shorter routes that don't exist.
- Using 0 or -1 for "unreachable." Those values look like real distances. Use
math.infor leave the key out so comparisons and sums behave sensibly. - Expecting a unique path. Tests that check for one specific path fail when ties exist. Check the path's weight instead.
Exercise
In the example graph, add an edge A→E with weight 3. What are the new values of δ(S, v) for all five vertices, and does any other distance change?
Show answer
E becomes reachable through S→A→E, so δ(S, E) = 2 + 3 = 5. The only edge out of E goes back to S, which already has distance 0, so no other distance changes: S = 0, A = 2, B = 3, C = 4, E = 5.
Exercise
Explain why optimal substructure means a single predecessor per vertex is enough to represent all shortest paths from s, even when several shortest paths exist.
Show answer
Every prefix of a shortest path is itself a shortest path. If prev[v] = u lies on some shortest path to v, then following one shortest path to u and taking the edge u→v gives a shortest path to v. Applying this repeatedly from v back to s rebuilds a complete shortest path. Tied alternatives aren't needed to get a correct answer, so storing one predecessor per vertex is enough. Together these predecessors form a shortest-path tree.
Exercise
You need the shortest driving time from every intersection in a city to a single hospital, on one-way streets. Which variant is this, and how do you solve it with an SSSP algorithm?
Show answer
This is the single-destination problem. Build the reversed graph, with each street u→v stored as v→u at the same travel time, and run SSSP from the hospital. The distance from the hospital to x in the reversed graph equals the driving time from x to the hospital in the original graph.