Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Edmonds-Karp Maximum Flow: A Practical Tutorial

Maximum flow finds the greatest amount of traffic, data, water or work that can pass through a directed network without exceeding any edge's capacity. Flow enters at a source, follows directed edges, and leaves at a sink. At every intermediate vertex, incoming flow must equal outgoing flow, so the task becomes a precise optimisation problem rather than an informal judgement about the busiest route.

The Edmonds-Karp algorithm for maximum flow is the breadth-first-search version of Ford-Fulkerson. It repeatedly finds a residual path with the fewest edges, sends as much flow as possible along that path, and adjusts the network so later choices can undo earlier ones. This tutorial develops the model, proves the stopping rule through the max-flow min-cut theorem, and provides Python code suitable for small and medium networks.

Modelling a Flow Network

Start by representing the network as a directed graph. Each vertex is a location or processing stage, and each edge (u \to v) carries an integer capacity (c(u,v)). Choose a source (s) and sink (t). A feasible flow assigns (f(u,v)) to each edge, keeps (0 \le f(u,v) \le c(u,v)), and conserves the total at every intermediate vertex. The objective is to maximise the value leaving (s), which must equal the value entering (t).

Road planning provides a tangible example. For a Sydney network, interchanges on the M4 and M8 motorway approaches can become vertices, while links between them carry hourly vehicle capacities. Melbourne's tram network offers another model: stops and interchanges are vertices, track sections are edges, and capacity can represent how many trams per hour a section can handle. Directional tracks fit directed edges naturally; a two-way street may need one edge in each direction.

Before coding, decide what one unit of flow means: vehicles per hour, packets per second, megalitres per day or tonnes of ore. Capacities must use compatible units and time intervals. The open, community-written approach described on about hello ML fits this kind of transparent problem: assumptions remain visible, and a reader can reproduce every step.

Residual Networks and Backward Capacity

Give every original edge (u \to v) residual capacity (r(u,v)=c(u,v)-f(u,v)). After sending flow through it, also allow a reverse edge (v \to u) with residual capacity (f(u,v)). This reverse edge is not physical traffic; it represents the algorithm's ability to cancel part of an earlier decision. Residual capacity therefore changes after every augmentation.

Suppose flow uses (u \to v), but a later path would be better without it. Sending flow along (v \to u) reduces (f(u,v)) and preserves conservation at both vertices. This ability matters because the first shortest path can occupy an edge needed by a better global arrangement. A purely forward implementation would be a greedy heuristic; the residual graph makes Edmonds-Karp exact.

Eventually BFS cannot reach the sink. Let (S) be the vertices still reachable from the source in the residual graph and (T) the rest. Every original edge from (S) to (T) is saturated, while no positive flow enters (S) from (T). The flow value is therefore the capacity of that cut. The max-flow min-cut theorem guarantees that no larger flow exists, which turns the BFS failure into a proof of optimality. The Prim algorithm tutorial offers a useful comparison because it also selects network edges systematically, but solves a different optimisation problem.

Finding Shortest Augmenting Paths

Each round has three phases. First, BFS explores only residual edges with positive capacity and records a parent for each discovered vertex, ensuring the first route to the sink uses the fewest edges. Second, walk backwards from the sink to the source and take the minimum residual capacity on that route; this is the bottleneck. Third, subtract the bottleneck from each forward residual edge and add it to each reverse edge, then add it to the total flow.

Take a network with capacities (S \to A=3), (S \to B=2), (A \to B=1), (A \to T=2), and (B \to T=3). The first BFS can use (S \to A \to T), sending two units. The next uses (S \to B \to T), sending another two. A third route, (S \to A \to B \to T), sends one unit. The reported maximum is five, equal to the cut containing the source edges, whose capacities are (3+2).

Choosing the shortest path is what gives Edmonds-Karp its efficiency guarantee. A path with fewer edges leaves fewer opportunities for a small bottleneck, and the standard analysis bounds the number of augmentations by (O(VE)). BFS also has predictable queue-based behaviour, unlike arbitrary path choices, which can wander through many low-capacity edges and stall.

A Python Implementation

The implementation below stores capacities as a list of dictionaries, with vertex numbers as indices. It returns the maximum-flow value and the source side of the final minimum cut, which is useful for diagnosis.

from collections import deque


def edmonds_karp(capacity, source, sink):
    residual = [row.copy() for row in capacity]
    total = 0
    n = len(residual)

    while True:
        parent = [None] * n
        parent[source] = source
        queue = deque([source])

        while queue and parent[sink] is None:
            u = queue.popleft()

            for v, cap in residual[u].items():
                if cap > 0 and parent[v] is None:
                    parent[v] = u

                    if v == sink:
                        break

                    queue.append(v)

        if parent[sink] is None:
            break

        amount = float("inf")
        v = sink

        while v != source:
            u = parent[v]
            amount = min(amount, residual[u][v])
            v = u

        v = sink

        while v != source:
            u = parent[v]
            residual[u][v] -= amount
            residual[v][u] = residual[v].get(u, 0) + amount
            v = u

        total += amount

    reachable = {v for v in range(n) if parent[v] is not None}
    return total, reachable


# Vertices: 0 = S, 1 = A, 2 = B, 3 = T
capacity = [
    {1: 3, 2: 2},
    {2: 1, 3: 2},
    {3: 3},
    {},
]

max_flow, source_side = edmonds_karp(capacity, 0, 3)

assert max_flow == 5
assert source_side == {0}

Trace the code with the small example above. The parent array records the BFS tree, amount becomes the route's bottleneck, and the update loop changes both forward and reverse residual capacities. Returning the final reachable set lets you inspect the minimum cut: sum the original capacities of edges leaving that set, and the result must equal the returned flow value.

Using adjacency lists gives (O(V+E)) space and (O(V+E)) time per BFS. Since Edmonds-Karp performs (O(VE)) augmentations, the overall worst-case bound is (O(VE^2)). For dense graphs, an adjacency matrix can make each BFS cost (O(V^2)). Real inputs also benefit from quick checks: reject negative capacities, require a distinct source and sink, and ensure every edge has a valid destination. A trie is unnecessary for direct lookups, though the trie implementation guide becomes relevant when a related routing model must find vertices or edges whose names share a prefix.

Worked Applications and Validation

Real models are easiest when a capacity represents a genuine physical or contractual limit. On Sydney roads, one bottleneck may be a motorway merge that cannot accept more vehicles each hour. In Melbourne, a tram section may have a lower capacity than the stops around it. These local networks show why the algorithm reports a throughput limit rather than guessing which route is fastest in traffic.

A larger Australian example is the Pilbara iron-ore chain linking mines, rail routes and the Port Hedland export terminal. A flow unit could be one tonne of ore per period, with conveyor, train and berth capacities constraining delivery. The market is export-oriented, so planners connect physical throughput with contracts and international demand. A model helps test whether a proposed expansion raises total export capacity rather than merely moving the queue.

Validate results by checking three invariants: flow stays within capacity, intermediate vertices conserve flow, and the maximum-flow value equals the minimum-cut capacity. Include cases with disconnected components, parallel edges, a direct source-to-sink edge and routes requiring a reverse adjustment. Australian teams may promise to have a yarn with network owners before accepting the model, but the final report should leave no ambiguity. Once these checks pass, Edmonds-Karp provides a compact and dependable maximum-flow computation.