Algorithm Search⌘K

Ford-Fulkerson algorithm in Python

Repeatedly augment flow along s-t paths in the residual graph until none remain.

File
ford_fulkerson.py, 98 lines
Level
I0 not checked yet
Toolchain
Python 3.14, pytest 9
Test framework
pytest
Run the tests
python3 -m pytest
ford_fulkerson.pyRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ford-fulkerson/. The authors are listed in prov/AM5BV8.jsonl.

from fractions import Fraction
from typing import Union

Number = Union[int, Fraction, float]


def ford_fulkerson(
    n: int, edges: list[tuple[int, int, Number]], s: int, t: int
) -> tuple[Number, list[Number], list[int]]:
    """Maximum s-t flow by augmenting paths found with depth-first search.

    The network has the vertices 0 .. n-1 and the directed edges (u, v, cap) of the
    list, with cap >= 0. Parallel, antiparallel and zero-capacity edges and self-loops
    are allowed; each edge keeps its own flow. Requires s != t.
    Returns (value, flow, source_side): flow[i] is the flow on edges[i], and
    source_side lists, in increasing order, the vertices reachable from s in the final
    residual graph, which form the source side of a minimum cut.
    With integer capacities the flow is integral and the time is O(m * value).
    With Fraction capacities the arithmetic is exact and the method terminates.
    With float capacities rounding can leave tiny residual capacities; use exact types.
    """
    if s == t:
        raise ValueError("source and sink must differ")
    head: list[int] = []  # arc 2i is edge i forward, arc 2i + 1 is edge i backward
    res: list[Number] = []  # residual capacity of each arc
    adj: list[list[int]] = [[] for _ in range(n)]
    for u, v, cap in edges:  # @line L1: f = 0, so c_f(e+) = c(e) and c_f(e-) = 0
        if cap < 0:
            raise ValueError("capacities must be nonnegative")
        adj[u].append(len(head))
        head.append(v)
        res.append(cap)
        adj[v].append(len(head))
        head.append(u)
        res.append(0)
    value: Number = 0
    while True:
        path = _dfs_path(n, adj, head, res, s, t)  # @line L2
        if path is None:
            break
        delta = min(res[a] for a in path)  # @line L3
        for a in path:  # @line L4
            res[a] -= delta  # @line L5: forward arc a raises f(e); backward arc lowers it
            res[a ^ 1] += delta  # @line L6
        value += delta
    seen = _reachable(n, adj, head, res, s)  # @line L7
    flow = [res[2 * i + 1] for i in range(len(edges))]
    return value, flow, [v for v in range(n) if seen[v]]  # @line L8


def _dfs_path(
    n: int, adj: list[list[int]], head: list[int], res: list[Number], s: int, t: int
) -> list[int] | None:
    """Arcs of an s-t path with positive residual capacities, or None.

    Depth-first search with an explicit stack of arcs, so deep graphs do not hit the
    recursion limit. Each vertex is entered at most once, so one call is O(n + m).
    """
    seen = [False] * n
    seen[s] = True
    nxt = [0] * n  # the next index of adj[u] to try
    path: list[int] = []  # arcs from s to the current vertex
    u = s
    while u != t:
        if nxt[u] < len(adj[u]):
            a = adj[u][nxt[u]]
            nxt[u] += 1
            v = head[a]
            if res[a] > 0 and not seen[v]:
                seen[v] = True
                path.append(a)
                u = v
        elif path:
            a = path.pop()  # dead end: go back along the last arc
            u = head[a ^ 1]
        else:
            return None
    return path


def _reachable(
    n: int, adj: list[list[int]], head: list[int], res: list[Number], s: int
) -> list[bool]:
    """Vertices reachable from s along arcs with positive residual capacity."""
    seen = [False] * n
    seen[s] = True
    stack = [s]
    while stack:
        u = stack.pop()
        for a in adj[u]:
            v = head[a]
            if res[a] > 0 and not seen[v]:
                seen[v] = True
                stack.append(v)
    return seen
test_ford_fulkerson.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ford-fulkerson/. The authors are listed in prov/AM5BV8.jsonl.

import random
from fractions import Fraction
from itertools import combinations

import pytest

from ford_fulkerson import ford_fulkerson

S, A, B, C, D, T = range(6)
RUNNING = [(S, A, 10), (S, C, 10), (A, B, 4), (A, C, 2), (A, D, 8), (C, D, 9), (D, B, 6), (B, T, 10), (D, T, 10)]


def min_cut_brute(n, edges, s, t):
    """Oracle: the least capacity over all 2^(n-2) s-t cuts."""
    others = [v for v in range(n) if v not in (s, t)]
    best = None
    for k in range(len(others) + 1):
        for extra in combinations(others, k):
            side = {s, *extra}
            cap = sum(c for u, v, c in edges if u in side and v not in side)
            best = cap if best is None else min(best, cap)
    return best


def check(n, edges, s, t, value, flow, side):
    """The flow is feasible, has the value, and the side is a cut of that capacity."""
    exc = [0] * n
    for (u, v, c), f in zip(edges, flow):
        assert 0 <= f <= c
        exc[u] -= f
        exc[v] += f
    for v in range(n):
        if v not in (s, t):
            assert exc[v] == 0
    assert -exc[s] == value
    assert s in side and t not in side
    cut = set(side)
    assert sum(c for u, v, c in edges if u in cut and v not in cut) == value


def test_running_example() -> None:
    value, flow, side = ford_fulkerson(6, RUNNING, S, T)
    assert value == 19
    assert side == [S, C]
    check(6, RUNNING, S, T, value, flow, side)


def test_backward_edge_needed() -> None:
    edges = [(0, 1, 1), (0, 2, 1), (1, 2, 1), (1, 3, 1), (2, 3, 1)]
    value, flow, side = ford_fulkerson(4, edges, 0, 3)
    assert value == 2
    check(4, edges, 0, 3, value, flow, side)


def test_no_path_and_zero_capacity() -> None:
    assert ford_fulkerson(3, [(0, 1, 5), (2, 1, 5)], 0, 2) == (0, [0, 0], [0, 1])
    assert ford_fulkerson(3, [(0, 1, 5), (1, 2, 0)], 0, 2) == (0, [0, 0], [0, 1])
    assert ford_fulkerson(2, [], 0, 1) == (0, [], [0])


def test_antiparallel_parallel_and_loops() -> None:
    edges = [(0, 1, 3), (1, 2, 2), (2, 1, 1), (2, 3, 2), (0, 2, 1), (1, 1, 7), (0, 1, 2)]
    value, flow, side = ford_fulkerson(4, edges, 0, 3)
    assert value == 2
    check(4, edges, 0, 3, value, flow, side)
    edges = [(0, 1, 4), (1, 0, 4), (1, 2, 3), (2, 1, 5)]
    value, flow, side = ford_fulkerson(3, edges, 0, 2)
    assert value == 3
    check(3, edges, 0, 2, value, flow, side)


def test_exact_rational_capacities() -> None:
    edges = [(0, 1, Fraction(1, 3)), (0, 2, Fraction(1, 2)), (1, 3, Fraction(1, 2)), (2, 3, Fraction(1, 4)), (2, 1, 1)]
    value, flow, side = ford_fulkerson(4, edges, 0, 3)
    assert value == Fraction(3, 4)
    check(4, edges, 0, 3, value, flow, side)


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        ford_fulkerson(2, [(0, 1, 1)], 0, 0)
    with pytest.raises(ValueError):
        ford_fulkerson(2, [(0, 1, -1)], 0, 1)


def test_large_capacities() -> None:
    big = 2**62
    edges = [(0, 1, big), (1, 2, big), (0, 2, 1)]
    assert ford_fulkerson(3, edges, 0, 2)[0] == big + 1


def test_random_against_brute_force_cut() -> None:
    rng = random.Random(4417)
    for _ in range(600):
        n = rng.randint(2, 6)
        edges = [(rng.randrange(n), rng.randrange(n), rng.randint(0, 6)) for _ in range(rng.randint(0, 12))]
        s, t = rng.sample(range(n), 2)
        value, flow, side = ford_fulkerson(n, edges, s, t)
        assert value == min_cut_brute(n, edges, s, t)
        check(n, edges, s, t, value, flow, side)

What the next level needs

  • the tests did not run in this build

Read the full page about Ford-Fulkerson algorithm