TExcelTAD
Home › Graph Algorithms › Shortest Paths, Negative Edges and Cycles

Shortest Paths, Negative Edges and Cycles

Breadth-first search finds paths with the fewest edges. Most route-finding problems care about something else: the total length in kilometres, the travel time, the price of the tickets, the probability of failure along the way. Each edge then carries a weight, and the best path is the one of least total weight. This section of the course solves the single-source version: from one source ss, find a lightest path to every vertex. This first lesson sets up the definitions, explains why negative weights are allowed but negative cycles are not, and proves the structural fact every shortest-path algorithm relies on. The DSA course has a gentler introduction.

Definitions and variants

Let G=(V,E)G = (V, E) be a directed graph with weights w:E→Rw : E \to \mathbb{R}. The weight of a path p=⟨v0,v1,…,vk⟩p = \langle v_0, v_1, \ldots, v_k \rangle is

w(p)=∑i=1kw(vi−1,vi)w(p) = \sum_{i=1}^{k} w(v_{i-1}, v_i)

and the shortest-path weight from uu to vv is

δ(u,v)={min⁡{w(p):p is a path from u to v}if a path exists∞otherwise\delta(u, v) = \begin{cases} \min \{ w(p) : p \text{ is a path from } u \text{ to } v \} & \text{if a path exists} \\ \infty & \text{otherwise} \end{cases}

A shortest path from uu to vv is any path pp with w(p)=δ(u,v)w(p) = \delta(u, v). Undirected graphs are handled by replacing each edge with two arcs of the same weight (as long as weights are non-negative; a negative undirected edge is a negative cycle of length two).

Variant Question Solved by
single-source δ(s,v)\delta(s, v) for one ss and every vv this section
single-destination δ(u,t)\delta(u, t) for every uu single-source on the reversed graph
single-pair δ(u,v)\delta(u, v) for one pair no known algorithm is asymptotically faster than single-source in the worst case
all-pairs δ(u,v)\delta(u, v) for every pair the next section, or single-source from every vertex

Optimal substructure

Lemma (subpaths of shortest paths are shortest paths). If p=⟨v0,…,vk⟩p = \langle v_0, \ldots, v_k \rangle is a shortest path from v0v_0 to vkv_k, then for all 0≤i≤j≤k0 \le i \le j \le k the subpath pij=⟨vi,…,vj⟩p_{ij} = \langle v_i, \ldots, v_j \rangle is a shortest path from viv_i to vjv_j.

Cut and paste: split pp into p0ip_{0i}, pijp_{ij} and pjkp_{jk}. If some path pij′p'_{ij} from viv_i to vjv_j were lighter than pijp_{ij}, then p0ip_{0i}, pij′p'_{ij}, pjkp_{jk} would be a path from v0v_0 to vkv_k lighter than pp. This is the optimal-substructure argument of dynamic programming, and every algorithm in this section is, at heart, a way of filling in the table δ(s,⋅)\delta(s, \cdot) in a valid order.

Negative weights and negative cycles

Negative edge weights make sense: a refund on a leg of a journey, an energy gain on a downhill stretch, a profit in a currency exchange. They are fine as long as no cycle reachable from ss has negative total weight. If one does, going around it again and again makes the path weight as small as we like, so δ(s,v)=−∞\delta(s, v) = -\infty for every vv that can be reached from the cycle. The program shows both situations. It computes, for k=1,2,…k = 1, 2, \ldots, the lightest weight of a walk (a path that may repeat vertices) with at most kk edges from AA. In the first graph the values settle; in the second, which adds the cycle B→F→G→BB \to F \to G \to B of weight −1-1, they keep falling.

python · try it yourself
INF = float("inf")

def lightest_walks(V, edges, s, kmax):
    d = {v: INF for v in V}
    d[s] = 0
    history = []
    for k in range(1, kmax + 1):
        nd = dict(d)
        for u, v, w in edges:
            if d[u] + w < nd[v]:
                nd[v] = d[u] + w
        d = nd
        history.append(dict(d))
    return history

base = [("A", "B", 6), ("A", "C", 2), ("C", "B", 3), ("B", "D", -2), ("C", "D", 7), ("D", "E", 1), ("C", "E", 8)]
print("no negative cycle:")
for k, d in enumerate(lightest_walks("ABCDE", base, "A", 6), 1):
    print(f"  k = {k}:", d)

cyc = base + [("B", "F", 2), ("F", "G", -4), ("G", "B", 1)]
print("with the cycle B -> F -> G -> B of weight -1:")
for k, d in enumerate(lightest_walks("ABCDEFG", cyc, "A", 12), 1):
    if k % 3 == 0:
        print(f"  k = {k:2}: B = {d['B']}, D = {d['D']}, E = {d['E']}")
no negative cycle:
  k = 1: {'A': 0, 'B': 6, 'C': 2, 'D': inf, 'E': inf}
  k = 2: {'A': 0, 'B': 5, 'C': 2, 'D': 4, 'E': 10}
  k = 3: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 5}
  k = 4: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
  k = 5: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
  k = 6: {'A': 0, 'B': 5, 'C': 2, 'D': 3, 'E': 4}
with the cycle B -> F -> G -> B of weight -1:
  k =  3: B = 5, D = 3, E = 5
  k =  6: B = 4, D = 2, E = 4
  k =  9: B = 3, D = 1, E = 3
  k = 12: B = 2, D = 0, E = 2

Without the cycle the values stop changing after 4 edges, because a shortest path never needs more than V−1V - 1 edges (below). With the cycle, every lap lowers BB, DD and EE by one more: their shortest-path weight is −∞-\infty, while AA and CC, which cannot be reached from the cycle, still have finite values. Bellman-Ford detects exactly this situation.

Shortest paths can be taken simple

If no negative cycle is reachable, a shortest path never needs a cycle. A cycle of positive weight can be cut out to make the path lighter; a cycle of weight zero can be cut out without changing the weight. So whenever δ(s,v)\delta(s, v) is finite, some simple shortest path exists, and a simple path has at most V−1V - 1 edges. That bound is why Bellman-Ford runs V−1V - 1 rounds.

The program checks it by brute force: it lists every simple path from AA in the first graph and compares the lightest with the walk values above.

python · try it yourself
base = [("A", "B", 6), ("A", "C", 2), ("C", "B", 3), ("B", "D", -2), ("C", "D", 7), ("D", "E", 1), ("C", "E", 8)]
adj = {}
for u, v, w in base:
    adj.setdefault(u, []).append((v, w))

best = {}
def walk(u, path, weight):
    if u not in best or weight < best[u][0]:
        best[u] = (weight, path)
    for v, w in adj.get(u, []):
        if v not in path:
            walk(v, path + [v], weight + w)

walk("A", ["A"], 0)
for v in sorted(best):
    weight, path = best[v]
    print(f"delta(A, {v}) = {weight:2}  via {' -> '.join(path)},  edges: {len(path) - 1}")
delta(A, A) =  0  via A,  edges: 0
delta(A, B) =  5  via A -> C -> B,  edges: 2
delta(A, C) =  2  via A -> C,  edges: 1
delta(A, D) =  3  via A -> C -> B -> D,  edges: 3
delta(A, E) =  4  via A -> C -> B -> D -> E,  edges: 4

Shortest-path trees

Like BFS, the algorithms of this section store a predecessor v.πv.\pi for every vertex instead of whole paths. When they finish, the edges (v.π,v)(v.\pi, v) form a shortest-path tree rooted at ss: a tree containing every vertex reachable from ss, in which the tree path from ss to vv is a shortest path in GG. It exists because of optimal substructure: if v.π=uv.\pi = u, a shortest path to uu followed by (u,v)(u, v) is a shortest path to vv. Shortest paths and shortest-path trees need not be unique; two paths of equal weight may both qualify.

The animation is a preview of the next lessons: Bellman-Ford on the first graph, relaxing the edges in the order listed, until the labels equal the distances printed above.

Test yourself

A graph has a cycle of total weight −3-3 that is reachable from ss, and vv is reachable from the cycle. What is δ(s,v)\delta(s, v)?

  1. −3-3
  2. The weight of the lightest simple path
  3. −∞-\infty
  4. ∞\infty

Why does a shortest path in a graph without negative cycles never need more than V−1V - 1 edges?

  1. Because weights are positive
  2. Because any cycle in it has non-negative weight and can be removed, leaving a simple path, which has at most V−1V - 1 edges
  3. Because BFS says so
  4. Because E≤V−1E \le V - 1

Which property lets shortest-path algorithms store only one predecessor per vertex?

  1. Negative weights
  2. Subpaths of shortest paths are shortest paths
  3. The graph is a DAG
  4. Edge weights are distinct