TExcelTAD
Home › Graph Algorithms › Edmonds-Karp: Shortest Augmenting Paths

Edmonds-Karp: Shortest Augmenting Paths

Ford-Fulkerson can need as many augmentations as the value of the maximum flow, because a bad path choice adds as little as 1 per round. Edmonds and Karp (1972), and independently Dinitz (1970), found the fix: always augment along a shortest augmenting path, counting edges, found by breadth-first search in the residual network. Then the number of augmentations is O(VE)O(VE) no matter how large the capacities are, and the whole algorithm runs in O(VE2)O(VE^2) time. This lesson states the algorithm, sketches the proof of the bound, and checks both lemmas of the proof on random networks. The DSA course shows the algorithm by example.

The algorithm

text
EDMONDS-KARP(G, s, t)
1  f = the zero flow
2  repeat
3      run BFS from s in the residual network G_f
4      if t was not reached:  return f
5      p = the BFS path from s to t                // a path with the fewest edges
6      augment f along p by c_f(p)

Each round costs O(E)O(E): the BFS is O(V+Ef)O(V + E_f) with Ef≤2EE_f \le 2E, and the augmentation O(V)O(V).

Watching it work

The animation is Edmonds-Karp on the network of Residual Networks. The BFS visits neighbours alphabetically; the third path is longer than the first two, as the analysis predicts, and it uses a backward edge.

python · try it yourself
from collections import deque

def edmonds_karp(cap, s, t):
    flow = {e: 0 for e in cap}
    def residual_from(u):
        out = []
        for (a, b), c in cap.items():
            if a == u and c - flow[(a, b)] > 0:
                out.append((b, 0, (a, b), c - flow[(a, b)]))     # forward edges sort first on ties
            if b == u and flow[(a, b)] > 0:
                out.append((a, 1, (a, b), flow[(a, b)]))
        return sorted(out)
    value, rounds = 0, 0
    while True:
        prev, q = {s: None}, deque([s])
        while q and t not in prev:
            u = q.popleft()
            for v, back, e, r in residual_from(u):
                if v not in prev:
                    prev[v] = (u, back, e, r); q.append(v)
        if t not in prev:
            S = sorted(prev)
            return value, flow, S
        steps, v = [], t
        while prev[v]:
            steps.append(prev[v]); v = prev[v][0]
        steps.reverse()
        b = min(r for _, _, _, r in steps)
        for u, back, e, r in steps:
            flow[e] += -b if back else b
        rounds += 1; value += b
        path = s + "".join(e[1] if not back else e[0] for _, back, e, _ in steps)
        print(f"round {rounds}: path {' -> '.join(path)} ({len(path) - 1} edges), bottleneck {b}, total {value}")

cap = {("S", "A"): 4, ("S", "C"): 3, ("A", "B"): 3, ("A", "D"): 6, ("C", "B"): 4, ("B", "T"): 2, ("D", "T"): 3}
value, flow, S = edmonds_karp(cap, "S", "T")
print("maximum flow", value, "| minimum cut S-side:", S)
round 1: path S -> A -> B -> T (3 edges), bottleneck 2, total 2
round 2: path S -> A -> D -> T (3 edges), bottleneck 2, total 4
round 3: path S -> C -> B -> A -> D -> T (5 edges), bottleneck 1, total 5
maximum flow 5 | minimum cut S-side: ['A', 'B', 'C', 'D', 'S']

Why O(VE)O(VE) augmentations

Let δf(s,v)\delta_f(s, v) be the BFS distance (number of edges) from ss to vv in the residual network GfG_f.

Lemma 1 (distances never decrease). During Edmonds-Karp, δf(s,v)\delta_f(s, v) never decreases for any vertex vv from one augmentation to the next.

Proof sketch

An augmentation along a shortest path can only remove residual edges (those that become full) and add residual edges (v,u)(v, u) that reverse path edges (u,v)(u, v). A path edge goes from distance dd to distance d+1d + 1, so the new reverse edge goes from distance d+1d + 1 back to dd: a step backwards in the BFS layers. Edges that go back a layer, or stay within one, cannot create a shortcut. Formally: suppose some vertex's distance decreased, take the one with the smallest new distance, and look at its predecessor uu on a new shortest path; the edge (u,v)(u, v) must have been added by the augmentation, so (v,u)(v, u) was on the old shortest path, giving δ(s,u)=δ(s,v)+1\delta(s, u) = \delta(s, v) + 1 in the old network and a contradiction with the new distances.

Lemma 2 (critical edges). An edge (u,v)(u, v) of the path is critical if its residual capacity equals the bottleneck; it disappears from the residual network after the augmentation. Each of the EE edges of GG can be critical at most V/2V/2 times (in either direction).

Proof sketch

When (u,v)(u, v) is critical, it lies on a shortest path, so δ(s,v)=δ(s,u)+1\delta(s, v) = \delta(s, u) + 1. It can reappear only after flow is pushed back along (v,u)(v, u), which requires (v,u)(v, u) on a later shortest path: then δ′(s,u)=δ′(s,v)+1≥δ(s,v)+1=δ(s,u)+2\delta'(s, u) = \delta'(s, v) + 1 \ge \delta(s, v) + 1 = \delta(s, u) + 2 by Lemma 1. So between two times that (u,v)(u, v) is critical, uu's distance grows by at least 2. Distances stay below VV (or become unreachable), so this happens at most V/2V/2 times.

Every augmentation has at least one critical edge, there are at most 2E2E residual edge directions, each critical O(V)O(V) times, so there are O(VE)O(VE) augmentations. At O(E)O(E) per augmentation the total is O(VE2)O(VE^2), a bound that does not mention the capacities at all.

Testing the lemmas

The program runs Edmonds-Karp on 300 random networks with capacities up to 1000. After every augmentation it recomputes the BFS distances and checks Lemma 1, and it counts how often each edge is critical (Lemma 2), comparing the number of augmentations with VEVE.

python · try it yourself
import random
from collections import deque

def run(n, cap, s, t):
    flow = {e: 0 for e in cap}
    adj = {u: [] for u in range(n)}
    for (a, b) in cap:
        adj[a].append((a, b)); adj[b].append((a, b))
    def res(u):
        for (a, b) in adj[u]:
            if a == u and cap[(a, b)] - flow[(a, b)] > 0:
                yield b, (a, b), cap[(a, b)] - flow[(a, b)], 1
            if b == u and flow[(a, b)] > 0:
                yield a, (a, b), flow[(a, b)], -1
    def bfs():
        dist, prev, q = {s: 0}, {s: None}, deque([s])
        while q:
            u = q.popleft()
            for v, e, r, sign in res(u):
                if v not in dist:
                    dist[v] = dist[u] + 1; prev[v] = (u, e, r, sign); q.append(v)
        return dist, prev
    critical, rounds, last = {}, 0, None
    while True:
        dist, prev = bfs()
        if last is not None:
            assert all(dist.get(v, n) >= last.get(v, n) for v in range(n)), "Lemma 1 violated"
        last = dist
        if t not in dist:
            return rounds, max(critical.values(), default=0)
        steps, v = [], t
        while prev[v]:
            steps.append(prev[v]); v = prev[v][0]
        b = min(r for _, _, r, _ in steps)
        for u, e, r, sign in steps:
            flow[e] += sign * b
            if r == b:
                critical[e] = critical.get(e, 0) + 1
        rounds += 1

rng = random.Random(33)
worst_ratio, worst_critical = 0, 0
for trial in range(300):
    n = rng.randint(4, 14)
    cap = {}
    for u in range(n):
        for v in range(n):
            if u != v and (v, u) not in cap and rng.random() < 0.3:
                cap[(u, v)] = rng.randint(1, 1000)
    rounds, most = run(n, cap, 0, n - 1)
    worst_ratio = max(worst_ratio, rounds / (n * max(1, len(cap))))
    worst_critical = max(worst_critical, most / (n / 2))
print("Lemma 1 held after every augmentation of 300 networks")
print(f"largest (augmentations / VE): {worst_ratio:.3f}")
print(f"largest (times one edge was critical / (V/2)): {worst_critical:.2f}")
Lemma 1 held after every augmentation of 300 networks
largest (augmentations / VE): 0.250
largest (times one edge was critical / (V/2)): 0.50

Both ratios stay well below 1: the O(VE)O(VE) bound is a worst case, and random networks need only a handful of augmentations. Capacities up to 1000 make no difference, in contrast with the zig-zag example of the previous lesson. The practice problem Maximum Flow can be solved with exactly this algorithm.

In C++

The standard C++ implementation stores edges in one array, each edge next to its reverse, so a backward residual edge is just index e ^ 1.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <queue>
#include <vector>

struct MaxFlow {
    struct Edge { int to, cap; };
    std::vector<Edge> edges;                     // edge e and its reverse e ^ 1
    std::vector<std::vector<int>> adj;
    explicit MaxFlow(int n) : adj(n) {}
    void add(int u, int v, int c) {
        adj[u].push_back(static_cast<int>(edges.size())); edges.push_back({v, c});
        adj[v].push_back(static_cast<int>(edges.size())); edges.push_back({u, 0});
    }
    long long run(int s, int t, int& rounds) {
        long long total = 0;
        rounds = 0;
        while (true) {
            std::vector<int> via(adj.size(), -1);
            std::queue<int> q;
            q.push(s);
            via[s] = -2;
            while (!q.empty() && via[t] == -1) {
                int u = q.front(); q.pop();
                for (int e : adj[u])
                    if (edges[e].cap > 0 && via[edges[e].to] == -1) { via[edges[e].to] = e; q.push(edges[e].to); }
            }
            if (via[t] == -1) return total;
            int b = 1 << 30;
            for (int v = t; v != s; v = edges[via[v] ^ 1].to) b = std::min(b, edges[via[v]].cap);
            for (int v = t; v != s; v = edges[via[v] ^ 1].to) { edges[via[v]].cap -= b; edges[via[v] ^ 1].cap += b; }
            total += b;
            ++rounds;
        }
    }
};

int main() {
    enum { S, A, B, C, D, T };
    MaxFlow g(6);
    g.add(S, A, 10); g.add(S, B, 7); g.add(A, B, 4); g.add(A, C, 5); g.add(B, D, 9);
    g.add(C, B, 3); g.add(C, T, 8); g.add(D, C, 4); g.add(D, T, 6);
    int rounds;
    long long f = g.run(S, T, rounds);
    std::printf("maximum flow %lld in %d augmentations\n", f, rounds);
    MaxFlow h(4);                                // the zig-zag network with M = 1000000
    h.add(0, 1, 1000000); h.add(0, 2, 1000000); h.add(1, 2, 1); h.add(1, 3, 1000000); h.add(2, 3, 1000000);
    f = h.run(0, 3, rounds);
    std::printf("zig-zag network: maximum flow %lld in %d augmentations\n", f, rounds);
}
maximum flow 14 in 4 augmentations
zig-zag network: maximum flow 2000000 in 2 augmentations

Test yourself

How does Edmonds-Karp choose its augmenting paths?

  1. The path with the largest bottleneck
  2. A path with the fewest edges, found by BFS in the residual network
  3. Any path found by DFS
  4. The path through the most vertices

What is the running time of Edmonds-Karp?

  1. O(E∣f∗∣)O(E \lvert f^* \rvert)
  2. O(VE2)O(VE^2)
  3. O(V2lg⁡V)O(V^2 \lg V)
  4. O(Elg⁡V)O(E \lg V)

Why can one edge be critical at most about V/2V/2 times?

  1. Because it then gets deleted from GG
  2. Between two times it is critical, the distance of its tail from ss grows by at least 2, and distances are less than VV
  3. Because capacities are integers
  4. Because BFS visits each vertex once