Sub topic 2
Single-Source vs. All-Pairs Shortest Paths
This chapter assumes you know what vertices, directed edges, adjacency lists and adjacency matrices are. It also assumes you can read Big-O notation and basic Python. The previous chapter introduced weighted directed graphs and negative edge weights. Here we state exactly what "shortest path" means, and then look at the two forms of the question that Bellman-Ford and Floyd-Warshall each answer.
Path Weight and Shortest-Path Distance
A path from u to v is a sequence of vertices u = x0, x1, ..., xk = v where each consecutive pair (x_i, x_{i+1}) is an edge. The weight of a path is the sum of its edge weights. The number of edges plays no part in it.
The shortest-path distance δ(u, v) is the minimum weight over all paths from u to v. Three cases matter:
| Situation | Value of `δ(u, v)` | How code represents it |
|---|---|---|
| At least one path exists, and no negative cycle can be inserted into it | A finite number (may be negative) | A number such as `5` or `-3` |
| No path from `u` to `v` exists | `+∞` | `math.inf` |
| A path exists that can pass through a negative cycle | `-∞` (undefined) | Reported as an error or a flag |
The third row is covered in the chapter on negative cycles. For now, assume the graph has none. Under that assumption the shortest walk between two vertices never repeats a vertex. Repeating a vertex would mean going around a cycle of non-negative weight, which cannot make the total smaller. So every shortest path has at most V - 1 edges. That fact returns later as the reason Bellman-Ford's round count is enough.
The Four Variants of the Problem
Textbooks list four variants. Two of them turn out to be the same problem in disguise.
- Single-pair: find
δ(s, t)for one fixed sourcesand targett. - Single-source: find
δ(s, v)for one sourcesand every vertexv. - Single-destination: find
δ(u, t)for every vertexuand one targett. - All-pairs: find
δ(u, v)for every pair of vertices.
Single-pair reduces to single-source. No known general algorithm finds one s-to-t distance faster in the worst case than computing distances from s to everything. Bellman-Ford can only be sure about t after it has done enough work to settle every vertex. In practice you run the single-source algorithm and read off dist[t].
Single-destination reduces to single-source. Reverse every edge, so (u, v, w) becomes (v, u, w). A path u → ... → t in the original graph becomes a path t → ... → u with the same weight in the reversed graph. One single-source run from t on the reversed graph gives the distance from every vertex to t.
That leaves two problems that really differ: single-source and all-pairs.
What Each Problem Outputs
The two problems produce outputs of different shapes. That difference drives the memory cost and how you reconstruct paths.
| Row | Single-source | All-pairs |
|---|---|---|
| Distances | Array `dist[v]`, size `V` | Matrix `dist[i][j]`, size `V × V` |
| Path information | Predecessor array `pred[v]`, size `V` | Next-hop matrix `nxt[i][j]`, size `V × V` |
| Structure of the paths | A **shortest-path tree** rooted at `s` | One shortest-path tree per source |
| Typical algorithm | Bellman-Ford, `O(VE)` | Floyd-Warshall, `O(V³)` |
| Negative-cycle scope | Detects cycles reachable from `s` | Detects every negative cycle in the graph |
The single-source output fits in a tree because of optimal substructure. Every vertex v needs only one parent: the vertex just before v on some shortest path from s. All-pairs needs a separate tree for every source, so it stores V times as much.
A Worked Example with a Reference Oracle
The running example graph for this tutorial has four vertices and five edges, one of them negative:
Before learning the efficient algorithms, it helps to have a slow but obviously correct oracle, meaning a reference implementation you can test the fast ones against. The code below lists every simple path by depth-first search. That gives correct answers whenever the graph has no negative cycle, because shortest paths are simple in that case. It runs in exponential time, so use it only on tiny graphs.
import math
def single_source_bruteforce(n, edges, s):
# Correct only when there is no negative cycle; exponential time.
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
dist = [math.inf] * n
def dfs(u, total, visited):
if total < dist[u]:
dist[u] = total
for v, w in adj[u]:
if v not in visited:
visited.add(v)
dfs(v, total + w, visited)
visited.remove(v)
dfs(s, 0, {s})
return dist
def all_pairs_by_repetition(n, edges):
# All-pairs as V independent single-source runs.
return [single_source_bruteforce(n, edges, s) for s in range(n)]
def single_destination(n, edges, t):
# Reverse every edge, then solve single-source from t.
reversed_edges = [(v, u, w) for u, v, w in edges]
return single_source_bruteforce(n, reversed_edges, t)
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print(single_source_bruteforce(4, edges, 0)) # [0, 4, 1, 5]
for row in all_pairs_by_repetition(4, edges):
print(row)
# [0, 4, 1, 5]
# [inf, 0, -3, 1]
# [inf, inf, 0, 4]
# [inf, inf, inf, 0]
print(single_destination(4, edges, 3)) # [5, 1, 4, 0]Several things in this output are worth noticing:
dist[0][2]is1, not5. The two-edge path0 → 1 → 2beats the direct edge because of the-3. A greedy algorithm that settles vertex 2 at distance 5 the moment it sees the direct edge gets this wrong. That is how negative weights break Dijkstra's algorithm.dist[1][3]is1through1 → 2 → 3, even though a direct edge of weight 6 exists.- The diagonal is all zeros. The empty path from a vertex to itself has weight 0. A diagonal entry below zero would mean a negative cycle, which Floyd-Warshall uses for detection in a later chapter.
- Row 0 of the all-pairs matrix equals the single-source answer from vertex 0, and column 3 equals the single-destination answer for vertex 3. The all-pairs matrix contains every single-source and single-destination answer.
Repetition vs. a Dedicated All-Pairs Algorithm
The function all_pairs_by_repetition shows the simplest way to solve all-pairs: run single-source once from every vertex. With Bellman-Ford that costs V · O(VE) = O(V²E). On a sparse graph, where E ≈ V, that is O(V³). On a dense graph, where E ≈ V², it grows to O(V⁴).
Floyd-Warshall solves all-pairs directly in O(V³) whatever the density. It has three tight nested loops over a matrix and a small constant factor. So the choice depends on the graph and on the questions you need to answer:
- You need distances from one source. Use a single-source algorithm, because computing a
V × Vmatrix wastes both time and memory. - You need distances between many or all pairs on a dense or small graph. Use Floyd-Warshall.
- You need all pairs on a large sparse graph. Johnson's algorithm runs Bellman-Ford once and then Dijkstra
Vtimes. A later chapter covers it.
Exercises
Exercise
In the example graph, add the edge (3, 0, 2). Without running code, what is the new value of dist[2][1] in the all-pairs matrix, and which path achieves it?
Show answer
The value is 10, through the path 2 → 3 → 0 → 1 with weights 4 + 2 + 4. Before the new edge, no path from 2 to 1 existed, so the value was inf. Check for negative cycles too: the cheapest cycle through the new edge is 0 → 1 → 2 → 3 → 0 with weight 4 - 3 + 4 + 2 = 7, which is positive, so the distances remain well defined.
Exercise
You need the shortest distance from every warehouse in a 50,000-vertex road graph to one central depot. Which problem variant is this, and how do you solve it with one run of a single-source algorithm?
Show answer
This is the single-destination problem. Reverse every edge, so (u, v, w) becomes (v, u, w), and run a single-source algorithm from the depot on the reversed graph. The distance it reports for each warehouse equals that warehouse's distance to the depot in the original graph. No all-pairs computation is needed.
Exercise
Why is singlesourcebruteforce correct when the graph has no negative cycles, even though it only explores simple paths?
Show answer
Any walk that repeats a vertex contains a cycle. With no negative cycles, every cycle has weight zero or more, so cutting the cycle out gives a walk that is no heavier. Repeating this leaves a simple path that is at least as short. So the minimum over simple paths equals the true shortest-path distance.