TExcelTAD
Home › Data Structures & Algorithms › Ford-Fulkerson

Ford-Fulkerson

The Ford-Fulkerson method (1956) computes a maximum flow by repeatedly finding an augmenting path: a path from the source to the sink along which more flow can be pushed. It keeps going until no augmenting path is left, and then the flow is maximum.

The residual graph

The key data structure is the residual graph. For each edge u → v with capacity c and current flow f, it contains:

  • a forward edge u → v with residual capacity c - f (how much more we can send), and
  • a backward edge v → u with residual capacity f (how much we could undo).

Pushing flow along a backward edge means cancelling some flow sent earlier and rerouting it. Without backward edges, a bad early choice could block the optimum forever.

The algorithm

  1. Start with zero flow everywhere: the residual graph equals the capacities.
  2. Find any path from S to T using only edges with residual capacity > 0 (Ford-Fulkerson usually uses DFS).
  3. Its bottleneck is the smallest residual capacity on the path. Push that much: subtract it from every forward residual edge on the path and add it to the corresponding backward edges.
  4. Repeat until no path exists. The total pushed is the max flow.

Why backward edges matter

The smallest example: two routes from S to T and a cross edge A → B. DFS (trying neighbours alphabetically) first takes the path through the cross edge, which blocks both direct routes. The second path then uses the backward edge B → A to cancel that flow:

python · try it yourself
def max_flow(capacity, source, sink):
    residual = {u: dict(vs) for u, vs in capacity.items()}
    for u in capacity:
        for v in capacity[u]:
            residual.setdefault(v, {}).setdefault(u, 0)    # backward edges start at 0

    def dfs(u, visited):
        if u == sink:
            return [u]
        visited.add(u)
        for v in sorted(residual[u]):
            if residual[u][v] > 0 and v not in visited:
                rest = dfs(v, visited)
                if rest:
                    return [u] + rest
        return None

    total = 0
    while (path := dfs(source, set())):
        bottleneck = min(residual[a][b] for a, b in zip(path, path[1:]))
        for a, b in zip(path, path[1:]):
            residual[a][b] -= bottleneck
            residual[b][a] += bottleneck
        uses_backward = any(b not in capacity.get(a, {}) or capacity[a][b] == 0
                            for a, b in zip(path, path[1:]))
        note = "  (uses a backward edge)" if uses_backward else ""
        print(f"path {' -> '.join(path)}, push {bottleneck}{note}")
        total += bottleneck
    return total

diamond = {"S": {"A": 1, "B": 1}, "A": {"B": 1, "T": 1}, "B": {"T": 1}}
print("max flow:", max_flow(diamond, "S", "T"))
path S -> A -> B -> T, push 1
path S -> B -> A -> T, push 1  (uses a backward edge)
max flow: 2

The second path S → B → A → T sends flow "backwards" along A → B, which cancels the first path's use of that edge. The net result is one unit along S → A → T and one along S → B → T.

The example network

Now the network from the intro (S→A 10, S→B 8, A→B 4, A→C 7, B→D 9, D→C 3, C→T 10, D→T 6). We also print the final flow on every original edge:

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

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

    def dfs(u, visited):
        if u == sink:
            return [u]
        visited.add(u)
        for v in sorted(residual[u]):
            if residual[u][v] > 0 and v not in visited:
                rest = dfs(v, visited)
                if rest:
                    return [u] + rest
        return None

    total = 0
    while (path := dfs(source, set())):
        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"augment {' -> '.join(path):<22} by {push:>2}  (total {total})")
    return total, residual

total, residual = ford_fulkerson(capacity, "S", "T")
print("max flow:", total)
for u in capacity:
    for v, c in capacity[u].items():
        print(f"  {u}->{v}: {c - residual[u][v]}/{c}")
augment S -> A -> B -> D -> C -> T by  3  (total 3)
augment S -> A -> B -> D -> T  by  1  (total 4)
augment S -> A -> C -> D -> T  by  3  (total 7)
augment S -> A -> C -> T       by  3  (total 10)
augment S -> B -> A -> C -> T  by  1  (total 11)
augment S -> B -> D -> C -> T  by  3  (total 14)
augment S -> B -> D -> T       by  2  (total 16)
max flow: 16
  S->A: 10/10
  S->B: 6/8
  A->B: 3/4
  A->C: 7/7
  B->D: 9/9
  C->T: 10/10
  D->C: 3/3
  D->T: 6/6

The final flow is 16, matching the minimum cut found in the intro. The fifth path, S → B → A → C → T, travels B → A backwards: it reroutes one unit that earlier went along A → B. Every edge's flow is within its capacity and conservation holds at A, B, C and D.

Finding the minimum cut

When the algorithm stops, the vertices still reachable from S in the residual graph form the source side of a minimum cut. The edges leaving that set are exactly the saturated bottleneck edges. This block reruns the algorithm and then searches the residual graph:

python · try it yourself
capacity = {
    "S": {"A": 10, "B": 8}, "A": {"B": 4, "C": 7}, "B": {"D": 9},
    "C": {"T": 10}, "D": {"C": 3, "T": 6}, "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)

def dfs(u, visited):
    if u == "T":
        return [u]
    visited.add(u)
    for v in sorted(residual[u]):
        if residual[u][v] > 0 and v not in visited:
            rest = dfs(v, visited)
            if rest:
                return [u] + rest
    return None

while (path := dfs("S", set())):
    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

reach, stack = {"S"}, ["S"]
while stack:
    u = stack.pop()
    for v, r in residual[u].items():
        if r > 0 and v not in reach:
            reach.add(v)
            stack.append(v)
cut = [(u, v, c) for u in capacity for v, c in capacity[u].items() if u in reach and v not in reach]
print("source side:", sorted(reach))
print("cut edges:", cut, "capacity:", sum(c for *_, c in cut))
source side: ['A', 'B', 'S']
cut edges: [('A', 'C', 7), ('B', 'D', 9)] capacity: 16

From S, the residual graph still reaches A (through the spare capacity on S → B and the backward edge B → A) and B. The edges leaving {S, A, B} are A → C and B → D; both are full, and 7 + 9 = 16 is exactly the max flow, as the max-flow min-cut theorem promises.

Complexity and a caveat

With integer capacities, each augmentation increases the flow by at least 1, so there are at most f augmentations (where f is the max flow), each costing O(E) for the DFS: O(E · f) in total. That can be very slow when capacities are huge, and with irrational capacities the method may not even terminate. Edmonds-Karp (next lesson) fixes this by always choosing the shortest augmenting path.

Test yourself

What is the bottleneck of an augmenting path?

  1. Its first edge
  2. The smallest residual capacity along the path
  3. The largest capacity in the graph
  4. The number of edges

What does a backward edge in the residual graph allow?

  1. Flow from T to S
  2. Cancelling (rerouting) flow that was sent earlier
  3. Doubling an edge's capacity
  4. Skipping vertices

After Ford-Fulkerson finishes, how do you find a minimum cut?

  1. Take the edges with the largest capacity
  2. Take the vertices reachable from S in the residual graph as the source side
  3. Remove the last augmenting path
  4. Run DFS from T in the original graph