TExcelTAD
Home › Data Structures & Algorithms › Edmonds-Karp

Edmonds-Karp

The Edmonds-Karp algorithm (1972) is Ford-Fulkerson with one specific rule: always augment along a shortest path (fewest edges) in the residual graph, found with breadth-first search. That small change makes the running time independent of the capacities: at most O(V · E) augmentations, so O(V · E²) in total.

Why the choice of path matters

Ford-Fulkerson allows any augmenting path, and an unlucky choice can be terrible. In this network the two direct routes can carry 2000 units in total, but a path chooser that always goes through the tiny middle edge A → B, alternately forwards (S → A → B → T) and backwards (S → B → A → T, using the residual edge B → A), pushes just 1 unit each time:

text
        1000         1000
   S ────────▶ A ────────▶ T
   │           │           ▲
   │1000       │1          │1000
   ▼           ▼           │
   └─────────▶ B ──────────┘
python · try it yourself
from collections import deque

trap = {"S": {"A": 1000, "B": 1000}, "A": {"B": 1, "T": 1000}, "B": {"T": 1000}, "T": {}}

def make_residual(capacity):
    residual = {u: dict(vs) for u, vs in capacity.items()}
    for u in capacity:
        for v in capacity[u]:
            residual[v].setdefault(u, 0)
    return residual

def augment(residual, path):
    push = min(residual[a][b] for a, b in zip(path, path[1:]))
    for a, b in zip(path, path[1:]):
        residual[a][b] -= push
        residual[b][a] += push
    return push

def unlucky(capacity):
    residual = make_residual(capacity)
    zigzag = [["S", "A", "B", "T"], ["S", "B", "A", "T"]]
    total = rounds = 0
    while True:
        path = zigzag[rounds % 2]
        if min(residual[a][b] for a, b in zip(path, path[1:])) == 0:
            break
        total += augment(residual, path)
        rounds += 1
    return total, rounds

def shortest_paths(capacity, s="S", t="T"):
    residual = make_residual(capacity)
    total = rounds = 0
    while True:
        parent, queue = {s: None}, deque([s])
        while queue:
            u = queue.popleft()
            for v in sorted(residual[u]):
                if residual[u][v] > 0 and v not in parent:
                    parent[v] = u
                    queue.append(v)
        if t not in parent:
            return total, rounds
        path = [t]
        while parent[path[-1]] is not None:
            path.append(parent[path[-1]])
        total += augment(residual, path[::-1])
        rounds += 1

print("unlucky zig-zag: max flow %d after %d augmentations" % unlucky(trap))
print("BFS (shortest):  max flow %d after %d augmentations" % shortest_paths(trap))
unlucky zig-zag: max flow 2000 after 2000 augmentations
BFS (shortest):  max flow 2000 after 2 augmentations

Both reach 2000, but the zig-zag needs 2000 augmentations where BFS needs 2. With capacities of a billion, the unlucky version would need two billion rounds. Edmonds-Karp rules out such choices: BFS always prefers the 2-edge paths S → A → T and S → B → T.

The algorithm

  1. Start with zero flow; the residual graph equals the capacities.
  2. Run BFS from S in the residual graph, using only edges with residual capacity > 0, recording each vertex's parent.
  3. If T was not reached, stop: the flow is maximum.
  4. Otherwise follow the parents back from T to get the shortest augmenting path, push its bottleneck, update forward and backward residual capacities, and go to step 2.

Edmonds-Karp on the example network

The same network as in the previous lessons (S→A 10, S→B 8, A→B 4, A→C 7, B→D 9, D→C 3, C→T 10, D→T 6):

python · try it yourself
from collections import deque

capacity = {
    "S": {"A": 10, "B": 8}, "A": {"B": 4, "C": 7}, "B": {"D": 9},
    "C": {"T": 10}, "D": {"C": 3, "T": 6}, "T": {},
}

def edmonds_karp(capacity, s, t):
    residual = {u: dict(vs) for u, vs in capacity.items()}
    for u in capacity:
        for v in capacity[u]:
            residual[v].setdefault(u, 0)
    total = 0
    while True:
        parent = {s: None}
        queue = deque([s])
        while queue and t not in parent:
            u = queue.popleft()
            for v in sorted(residual[u]):
                if residual[u][v] > 0 and v not in parent:
                    parent[v] = u
                    queue.append(v)
        if t not in parent:
            return total, residual
        path = [t]
        while parent[path[-1]] is not None:
            path.append(parent[path[-1]])
        path.reverse()
        push = min(residual[a][b] for a, b in zip(path, path[1:]))
        for a, b in zip(path, path[1:]):
            residual[a][b] -= push
            residual[b][a] += push
        total += push
        print(f"BFS path {' -> '.join(path):<20} ({len(path) - 1} edges), push {push:>2}, total {total}")

total, residual = edmonds_karp(capacity, "S", "T")
print("max flow:", total)
BFS path S -> A -> C -> T     (3 edges), push  7, total 7
BFS path S -> B -> D -> T     (3 edges), push  6, total 13
BFS path S -> B -> D -> C -> T (4 edges), push  2, total 15
BFS path S -> A -> B -> D -> C -> T (5 edges), push  1, total 16
max flow: 16

The paths get longer over time: first two 3-edge paths, then a 4-edge one and finally a 5-edge one. That is the heart of the correctness proof: the BFS distance from S to each vertex never decreases, and every augmentation saturates at least one edge on a shortest path, which bounds the number of augmentations by O(V · E). Compare: the DFS-based run in the previous lesson needed 7 augmentations on this network; Edmonds-Karp needs 4.

Application: bipartite matching

Three developers and three projects; each developer is qualified for some projects. How many developers can be assigned, one project each? Connect S to every developer and every project to T with capacity 1, plus a capacity-1 edge for each qualification. The max flow is the size of the best matching, and the edges carrying flow say who goes where:

python · try it yourself
from collections import deque

skills = {"Ana": ["web", "data"], "Ben": ["web"], "Cleo": ["data", "mobile"]}
capacity = {"S": {}, "T": {}}
for dev, projects in skills.items():
    capacity["S"][dev] = 1
    capacity[dev] = {p: 1 for p in projects}
    for p in projects:
        capacity.setdefault(p, {"T": 1})

residual = {u: dict(vs) for u, vs in capacity.items()}
for u in capacity:
    for v in capacity[u]:
        residual[v].setdefault(u, 0)

matched = 0
while True:
    parent, queue = {"S": None}, deque(["S"])
    while queue:
        u = queue.popleft()
        for v in sorted(residual[u]):
            if residual[u][v] > 0 and v not in parent:
                parent[v] = u
                queue.append(v)
    if "T" not in parent:
        break
    v = "T"
    while parent[v] is not None:
        residual[parent[v]][v] -= 1
        residual[v][parent[v]] += 1
        v = parent[v]
    matched += 1

print("developers assigned:", matched)
for dev, projects in skills.items():
    for p in projects:
        if residual[dev][p] == 0:
            print(f"  {dev} -> {p}")
developers assigned: 3
  Ana -> data
  Ben -> web
  Cleo -> mobile

All three developers get a project. Here the searches happened to give Ana data straight away. Had Ana been given web first, Ben's path would have used the backward edge web → Ana to move her to data: the residual graph lets the algorithm rearrange earlier assignments to make room.

Summary

Ford-Fulkerson (DFS) Edmonds-Karp (BFS)
Path choice any augmenting path a shortest augmenting path
Number of augmentations up to f (the flow value) O(V · E)
Time O(E · f) O(V · E²)
Depends on capacities? yes no

Faster algorithms exist (Dinic's algorithm, push-relabel), but Edmonds-Karp is short, reliable and fast enough for many practical networks.

Test yourself

How does Edmonds-Karp choose its augmenting paths?

  1. Largest bottleneck first
  2. Shortest path (fewest edges) found by BFS
  3. Random paths
  4. Depth-first, alphabetically

Why can plain Ford-Fulkerson be slow on the "trap" network?

  1. Each search is slower than BFS
  2. An unlucky path choice keeps going through the capacity-1 edge, pushing only 1 unit per augmentation
  3. It never terminates
  4. It ignores backward edges

In the bipartite matching model, what capacity do the edges have?

  1. 0
  2. 1
  3. The number of developers
  4. Infinity