Algorithm Search⌘K

Algorithmadvanced

Boykov-Kolmogorov max-flow algorithm

Also called BK max-flow, BK algorithm.

An augmenting path max-flow algorithm that grows search trees from the source and the sink and repairs them after each augmentation instead of starting again. Fast on vision grids.

Time
O(m n C) worst · averageO(n + m) best
Space
O(n + m) extra
Where
C = the capacity of a minimum cut with integer capacities; m = the number of edges; n = the number of nodes
Properties
deterministicexactofflineiterative
Origin
Yuri Boykov, Vladimir Kolmogorov, 2004

The Boykov-Kolmogorov algorithm computes a maximum flow and a minimum cut of a directed graph with a source ss and a sink tt. It is an augmenting path method in the family of Ford-Fulkerson, but it does not search for each path from the start. It keeps two search trees in the residual graph: the S tree grows from the source, and the T tree grows into the sink. When the trees touch, the path through the meeting edge is augmented. The saturated edges break the trees into pieces, and the pieces are joined back to the trees by an adoption step, so most of the search work is reused. The worst case bound is weaker than that of Edmonds-Karp, Dinic or push-relabel, but on the grid graphs of vision, with a few edges per pixel and many short paths, the algorithm was faster than those codes in the experiments of Boykov and Kolmogorov (2004). It is the usual solver for the cuts of alpha-expansion, graph cut segmentation and the other graph-representable energies.

In plain words

Water must go from a source to a sink through pipes. Two teams explore the network. One team starts at the source and the other at the sink, and each team keeps a tree of the pipes it has used to reach places. When the two teams meet, there is a route from the source to the sink, and you send as much water along it as the narrowest pipe allows. That pipe is now full, so some places lose their route back to their team. Instead of starting over, each lost place looks at its neighbors for another way back. Only places with no way back are given up. When the teams can no longer meet, the places the source team holds are the cheapest cut.

The problem

Input. A directed graph with nn nodes and mm edges, two nodes s≠ts \ne t, and a capacity c(u,v)≥0c(u, v) \ge 0 on each edge. Parallel and opposite edges are allowed.

Output. A maximum flow from ss to tt, and a minimum cut, given as its source side SS.

The residual capacity of an edge u→vu \to v is r(u→v)=c(u,v)−f(u,v)+f(v,u)r(u \to v) = c(u, v) - f(u, v) + f(v, u): the code stores each edge with its reverse and moves capacity between them. Each node is in the S tree, in the T tree, or free. In the S tree the parent edge of qq is an edge p→qp \to q with r>0r > 0, and in the T tree it is an edge q→pq \to p with r>0r > 0. Active nodes, in a FIFO queue AA, are the nodes of the trees that may still grow. Orphans, in a list OO, are nodes that lost their parent edge.

The algorithm

  1. BK-MAX-FLOW(G, s, t)
  2. 1tree[s] ← S; tree[t] ← T; tree[v] ← free for the other nodes; parent[s], parent[t] ← terminal
  3. 2A ← (s, t); O ← empty; flow ← 0
  4. 3loop
  5. 4e ← GROW() ▷ an edge from an S node to a T node, or nil
  6. 5if e = nil then return flow and the cut S = {v : tree[v] = S}
  7. 6P ← the parent edges from s to the tail of e, then e, then the parent edges to t
  8. 7Δ ← the least residual capacity on P; push Δ along P; flow ← flow + Δ
  9. 8for each edge of P except e that is now saturated do
  10. 9if it is an S edge p → q then parent[q] ← none; add q to O
  11. 10if it is a T edge p → q then parent[p] ← none; add p to O
  12. 11while O is not empty do take p from O; ADOPT(p)
  13. GROW()
  14. 12while A is not empty do
  15. 13p ← the front of A; if tree[p] = free then remove it and go to the next node
  16. 14for each neighbor q with r(p → q) > 0 if p is in S, or r(q → p) > 0 if p is in T do
  17. 15if tree[q] = free then tree[q] ← tree[p]; parent[q] ← the edge between p and q; add q to A
  18. 16else if tree[q] ≠ tree[p] then return the edge between p and q, directed from S to T
  19. 17remove p from A
  20. 18return nil
  21. ADOPT(p)
  22. 19for each neighbor q in the tree of p, with r(q → p) > 0 in S or r(p → q) > 0 in T do
  23. 20if the parent edges from q reach a terminal then parent[p] ← that edge; return
  24. 21for each neighbor q in the tree of p do
  25. 22if r(q → p) > 0 in S, or r(p → q) > 0 in T then add q to A
  26. 23if parent[q] is the edge between p and q then parent[q] ← none; add q to O
  27. 24tree[p] ← free

The main loop has three stages, the same as in Section 3.2 of the paper. Growth (lines L12 to L18) is a breadth-first search from both terminals at once over the residual graph; it stops at the first edge that joins the trees and keeps the node at the front of AA, so the next growth stage starts from where it stopped. Augmentation (lines L6 to L10) pushes the bottleneck along the path. The saturated edges are cut out of the trees, and the nodes below them become orphans. Adoption (lines L19 to L24) gives each orphan a new parent in its own tree if one exists with a residual edge and a chain to the terminal; otherwise the orphan becomes free, its children become orphans, and its neighbors that could reach it become active again so that a later growth stage can take it back.

Example

Take ss, aa, bb, tt and the edges s→as \to a of capacity 3, s→bs \to b of 2, a→ba \to b of 1, a→ta \to t of 2 and b→tb \to t of 3, scanned in this order.

step stage what happens flow
1 growth ss adds aa and bb to S; tt finds the S node aa through a→ta \to t 0
2 augment path s→a→ts \to a \to t, Δ=2\Delta = 2; a→ta \to t is the bridge, so no orphan 2
3 growth tt finds the S node bb through b→tb \to t 2
4 augment path s→b→ts \to b \to t, Δ=2\Delta = 2; s→bs \to b is saturated, bb is an orphan 4
5 adopt bb takes aa as parent through a→ba \to b (residual 1), since aa hangs from ss 4
6 growth tt finds bb through b→tb \to t (residual 1) 4
7 augment path s→a→b→ts \to a \to b \to t, Δ=1\Delta = 1; s→as \to a and a→ba \to b are saturated, bb and aa are orphans 5
8 adopt bb and then aa find no parent in S and become free 5
9 growth tt has no residual edge from a free or S node, and AA empties 5

The maximum flow is 5, and the final S tree is {s}\{s\}, the cut s→as \to a, s→bs \to b of capacity 3+2=53 + 2 = 5. Step 5 is the point of the method: the tree of step 1 is repaired, not built again.

Correctness

The full proof is in proofs/correctness.md. It keeps three invariants: the stored capacities are the residual capacities of a feasible flow; every tree edge has positive residual capacity in the direction of its tree, and the parent edges lead to the terminal without a cycle; and a passive S node has all its residual out-neighbors in S, a passive T node all its residual in-neighbors in T. Growth keeps them because a node leaves AA only after all its neighbors were seen. Augmentation keeps them because saturated tree edges make orphans, and the new reverse edges either join two nodes of the same tree or leave T toward S. Adoption keeps them because a new parent must have a chain to the terminal, which cannot pass through the orphan, and because a node that becomes free activates every neighbor that the third invariant could break. At the end AA is empty, so no residual edge leaves the S tree. Then the edges out of the S tree are saturated and the edges into it are empty, the flow value equals the cut capacity, and by the max-flow min-cut theorem both are optimal.

Proof: Correctness of the Boykov-Kolmogorov max-flow algorithmfull

We prove that BK-MAX-FLOW, with integer capacities, stops after at most ∣C∣|C| augmentations, where ∣C∣|C| is the capacity of a minimum cut, and that it returns a maximum flow ff and a minimum cut whose source side is the final S tree. Write r(u→v)r(u \to v) for the residual capacity of the stored edge from uu to vv. A node is active when it is in the queue AA, and passive when it is in a tree and not in AA.

Invariants

Between two lines of the main loop the following hold.

  1. Flow. The stored capacities are the residual capacities of a feasible flow ff of value flow\textit{flow}.
  2. Tree edges. If parent[q]\textit{parent}[q] is an edge p→qp \to q of an S node qq, then tree[p]=S\textit{tree}[p] = S and r(p→q)>0r(p \to q) > 0. If it is an edge q→pq \to p of a T node qq, then tree[p]=T\textit{tree}[p] = T and r(q→p)>0r(q \to p) > 0. Outside the adoption stage no node has the parent NONE, and the parent edges lead from each S node to ss and from each T node to tt without a cycle.
  3. Passive nodes. If pp is a passive S node and r(p→q)>0r(p \to q) > 0, then tree[q]=S\textit{tree}[q] = S. If pp is a passive T node and r(q→p)>0r(q \to p) > 0, then tree[q]=T\textit{tree}[q] = T.

At the start only ss and tt are in trees and both are active, so all three hold.

Growth (lines L12 to L18). Line L15 gives a free node qq the tree of pp and the edge between them, which has positive residual capacity in the right direction by the test of line L14; qq becomes active, and its parent chain is the edge to pp followed by the chain of pp. So invariant 2 holds. A node leaves AA at line L17 only after all its edges were scanned and every neighbor qq with a residual edge in the right direction was either put in the same tree or found in the other tree; the second case returns at line L16 before line L17, so at line L17 every such qq is in the same tree. Residual capacities do not change during growth, so invariant 3 holds for pp.

Augmentation (lines L6 to L10). Line L16 returns an edge a→ca \to c with tree[a]=S\textit{tree}[a] = S, tree[c]=T\textit{tree}[c] = T and r(a→c)>0r(a \to c) > 0. By invariant 2 the parent chains give a path from ss to aa and from cc to tt of edges with positive residual capacity, so line L6 builds an augmenting path PP and Δ>0\Delta > 0. Pushing Δ\Delta along PP keeps capacity and conservation, so invariant 1 holds with the value increased by Δ\Delta. Residual capacities change only on PP and on the reverse edges of PP. An edge of PP that becomes saturated is a tree edge or the bridge. Lines L9 and L10 cut the saturated tree edges and make their children orphans, so the remaining tree edges still have positive residual capacity. For invariant 3: a reverse edge v→uv \to u of an edge u→vu \to v of PP gains capacity. If u→vu \to v is in the S part, then both ends are in S, and the new residual edge joins two S nodes, which invariant 3 allows. The same holds in the T part. For the bridge a→ca \to c, the new residual edge is c→ac \to a. It leaves the T node cc and enters the S node aa, and invariant 3 says nothing about the edges out of a T node or into an S node.

Adoption (lines L19 to L24). An orphan pp is given a new parent qq at line L20 only if qq is in the same tree, the edge between them has positive residual capacity in the right direction, and the chain of qq reaches a terminal. That chain does not pass through pp, because pp has the parent NONE, so no cycle forms and invariant 2 holds for pp. If no such qq exists, pp becomes free at line L24. Before that, line L22 makes active each node qq of the same tree with a residual edge toward pp (for S) or from pp (for T). These are exactly the passive nodes for which invariant 3 would fail when pp leaves the tree. Line L23 makes the children of pp orphans, because their chain went through pp. When the orphan set is empty, every node in a tree has a chain to a terminal again, and invariants 2 and 3 hold.

The final state is a minimum cut

The loop stops at line L5 when growth finds no bridge and AA is empty. Then every node of the S tree is passive, so by invariant 3 every residual edge out of an S node goes to an S node. Let SS be the set of S nodes. It contains ss, and it does not contain tt, because tt is always in T. No residual edge leaves SS. So every edge from SS to the rest carries flow equal to its capacity, and every edge into SS carries no flow, because a positive flow on v→uv \to u with u∈Su \in S would give the residual edge u→vu \to v. The value of ff is the net flow across the cut, so it equals the capacity of the cut SS. By weak duality every flow is at most every cut, so ff is a maximum flow and SS is a minimum cut, which is the max-flow min-cut theorem. The returned source side is SS.

Termination

With integer capacities each Δ\Delta is a positive integer, and the value of a flow is at most ∣C∣|C|, so there are at most ∣C∣|C| augmentations. Between two augmentations, the work is finite and bounded as follows.

  • Growth. No node leaves a tree during growth, so a free node joins a tree at most once and enters AA at most once. Each node in AA is scanned once and then removed at line L17, except the node at which a bridge is found, which stays at the front. So one growth stage scans each edge O(1)O(1) times, in O(n+m)O(n + m) time.
  • Adoption. A node with a chain to a terminal keeps it for the rest of the adoption stage: a node gets the parent NONE only when its parent becomes free, and only an orphan becomes free. So a node is an orphan at most once in each adoption stage. Processing an orphan pp scans its edges twice and follows a chain of at most nn nodes for each candidate parent, in O(ndeg⁡p)O(n \deg p) time, and the sum over all nodes is O(mn)O(m n).

So the time between two augmentations is O(mn)O(m n), and the total time is O(mn∣C∣)O(m n |C|). Boykov and Kolmogorov state the bound O(mn2∣C∣)O(m n^2 |C|); the count above is a little finer for this version, and neither bound is polynomial in the input size. □\square

Complexity

The model is the word RAM with integer capacities.

  • Augmentations. Each augmentation adds at least 1, and the flow is at most the minimum cut capacity CC, so there are at most CC augmentations. This is the bound of the paper, Section 3.
  • Work between two augmentations. A growth stage scans each node at most once, in O(n+m)O(n + m) time. In an adoption stage each node is an orphan at most once, and each candidate parent costs a walk of at most nn nodes to check its chain, so the stage takes O(mn)O(m n) time.
  • Total. O(mnC)O(m n C) time. Boykov and Kolmogorov state O(mn2C)O(m n^2 C); the count in the proof is a little finer. Both depend on CC, so the algorithm is not even polynomial, while Dinic takes O(n2m)O(n^2 m) and push-relabel O(n3)O(n^3) or better.
  • In practice. The paper measured it on segmentation, stereo and restoration graphs and found it faster than Dinic and the push-relabel codes of the time in most of the tests. This is an observation on those graphs, not a bound: the trees are shallow, paths are short, and adoption usually finds a parent nearby.
  • Space. Two arrays of 2m2m edges for the residual graph, and O(n)O(n) for the trees, the queue and the orphan list.

Properties

  • Exact. It returns a maximum flow and a minimum cut, like every Ford-Fulkerson method on integer capacities.
  • Not strongly polynomial. The bound depends on CC. With irrational capacities a Ford-Fulkerson method need not stop, and this one has no special protection against that.
  • Paths are not shortest. The first path found by a fresh search is shortest, but after adoption the trees are not breadth-first trees, so the paths can be long. This is why the bound of Edmonds-Karp does not apply.
  • Source side. The final S tree is the set of nodes that ss reaches in the residual graph, which is the smallest source side of a minimum cut.

Variants and improvements

  • Distance and time stamps. The code of the authors marks the nodes whose chain to a terminal was checked in the current stage, with their distance to the terminal, so that a later walk can stop early and an orphan can prefer a close parent (Section 3.3 of the paper).
  • Reuse between cuts. In alpha-expansion and in interactive segmentation many cuts are solved on graphs that differ a little. Kohli and Torr (2007) reuse the flow and the trees of the last cut ("dynamic graph cuts").
  • Incremental breadth-first search. Goldberg, Hed, Kaplan, Tarjan and Werneck (2011) keep the trees breadth-first and get a strongly polynomial bound with similar speed on vision graphs.
  • Grid codes. For regular grids, the neighbors can be computed instead of stored, which saves memory on large volumes.

When to use it

Use it for the min cuts of energy minimization in vision and graphics: graph cut segmentation, Boykov-Jolly interactive segmentation, the moves of alpha-expansion and alpha-beta swap, and QPBO. Use push-relabel or a pseudoflow code on large graphs with long paths, such as dense 3D grids with many neighbors, and use a strongly polynomial method when a worst case guarantee matters.

Pitfalls

  • Floating point capacities. A small residual capacity can stay positive after an augmentation by rounding, and the loop can then make very many tiny augmentations. Scale the energies to integers, or treat capacities below a tolerance as zero.
  • The origin walk. Without marks, each adoption walks the whole chain to the terminal. On deep trees this makes adoption slow. Use the time stamps of the paper.
  • Infinite capacities. Hard constraints are often written as infinite edges. Use a large finite number that is larger than the sum of all finite capacities, and check that no path of only such edges joins ss and tt.
  • Reading the cut. The source side is the S tree, not the set of free nodes plus S. Free nodes at the end belong to the sink side.
  • Speed claims. The speed is measured on grid graphs. Do not expect the same speed on graphs with long paths or high degree.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

boykov_kolmogorov_max_flow.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boykov-kolmogorov-max-flow/. The authors are listed in prov/FXPM4P.jsonl.
"""The Boykov-Kolmogorov max-flow algorithm.

The graph has nodes 0 .. n - 1 and directed edges (u, v, capacity) with
nonnegative capacities. Each input edge k is stored as the residual edge
2k (u -> v) and its reverse 2k + 1 (v -> u, residual capacity 0 at the
start), so the reverse of edge e is e ^ 1.

Two search trees are kept: S grows from the source along edges with
residual capacity, T grows into the sink along edges with residual
capacity. parent[v] is the index of the tree edge that joins v to its
parent: the edge parent -> v in S, and the edge v -> parent in T.
"""

from __future__ import annotations

from collections import deque
from typing import List, Sequence, Tuple

FREE, SRC, SNK = 0, 1, 2
TERMINAL = -1  # parent value of s and t
NONE = -2  # parent value of an orphan or a free node


def bk_max_flow(n: int, edges: Sequence[Tuple[int, int, int]], s: int,
                t: int) -> Tuple[int, List[bool], List[int]]:
    """Return (flow value, source side of a minimum cut, flow on each edge).

    The source side is the final S tree, which is the set of nodes that
    the source reaches in the residual graph.
    """
    if s == t:
        raise ValueError("source and sink must differ")
    adj: List[List[int]] = [[] for _ in range(n)]
    to: List[int] = []
    cap: List[int] = []
    for (u, v, c) in edges:
        if c < 0:
            raise ValueError("capacities must be nonnegative")
        adj[u].append(len(to))
        to.append(v)
        cap.append(c)
        adj[v].append(len(to))
        to.append(u)
        cap.append(0)

    tree = [FREE] * n  # @line L1
    parent = [NONE] * n  # @line L1
    tree[s], tree[t] = SRC, SNK  # @line L1
    parent[s] = parent[t] = TERMINAL  # @line L1
    active = deque([s, t])  # @line L2
    in_active = [False] * n  # @line L2
    in_active[s] = in_active[t] = True  # @line L2
    orphans: deque = deque()  # @line L2
    flow = 0  # @line L2

    def make_active(v: int) -> None:
        if not in_active[v]:
            in_active[v] = True
            active.append(v)

    def grow() -> int:
        """Return an edge from a node of S to a node of T, or -1."""
        while active:  # @line L12
            p = active[0]  # @line L13
            if tree[p] == FREE:  # @line L13
                active.popleft()  # @line L13
                in_active[p] = False  # @line L13
                continue  # @line L13
            for e in adj[p]:  # @line L14
                q = to[e]
                if tree[p] == SRC:
                    if cap[e] <= 0:  # @line L14
                        continue
                    if tree[q] == FREE:  # @line L15
                        tree[q], parent[q] = SRC, e  # @line L15
                        make_active(q)  # @line L15
                    elif tree[q] == SNK:  # @line L16
                        return e  # @line L16
                else:
                    if cap[e ^ 1] <= 0:  # @line L14
                        continue
                    if tree[q] == FREE:  # @line L15
                        tree[q], parent[q] = SNK, e ^ 1  # @line L15
                        make_active(q)  # @line L15
                    elif tree[q] == SRC:  # @line L16
                        return e ^ 1  # @line L16
            active.popleft()  # @line L17
            in_active[p] = False  # @line L17
        return -1  # @line L18

    def has_terminal_origin(q: int) -> bool:
        while parent[q] != TERMINAL:
            if parent[q] == NONE:
                return False
            e = parent[q]
            q = to[e ^ 1] if tree[q] == SRC else to[e]
        return True

    def adopt(p: int) -> None:
        side = tree[p]
        for e in adj[p]:  # @line L19
            q = to[e]
            if tree[q] != side:
                continue
            # The candidate parent edge: q -> p in S, p -> q in T.
            pe = e ^ 1 if side == SRC else e
            if cap[pe] > 0 and has_terminal_origin(q):  # @line L20
                parent[p] = pe  # @line L20
                return  # @line L20
        for e in adj[p]:  # @line L21
            q = to[e]
            if tree[q] != side:
                continue
            pe = e ^ 1 if side == SRC else e
            if cap[pe] > 0:  # @line L22
                make_active(q)  # @line L22
            child_edge = e if side == SRC else e ^ 1
            if parent[q] == child_edge:  # @line L23
                parent[q] = NONE  # @line L23
                orphans.append(q)  # @line L23
        tree[p] = FREE  # @line L24

    while True:  # @line L3
        bridge = grow()  # @line L4
        if bridge < 0:  # @line L5
            break  # @line L5
        path = [bridge]  # @line L6
        a = to[bridge ^ 1]  # @line L6
        while parent[a] != TERMINAL:  # @line L6
            path.append(parent[a])  # @line L6
            a = to[parent[a] ^ 1]  # @line L6
        c = to[bridge]  # @line L6
        while parent[c] != TERMINAL:  # @line L6
            path.append(parent[c])  # @line L6
            c = to[parent[c]]  # @line L6
        delta = min(cap[e] for e in path)  # @line L7
        for e in path:  # @line L7
            cap[e] -= delta  # @line L7
            cap[e ^ 1] += delta  # @line L7
        flow += delta  # @line L7
        for e in path[1:]:  # @line L8
            if cap[e] == 0:  # @line L8
                head, tail = to[e], to[e ^ 1]
                if tree[head] == SRC and tree[tail] == SRC:  # @line L9
                    parent[head] = NONE  # @line L9
                    orphans.append(head)  # @line L9
                elif tree[head] == SNK and tree[tail] == SNK:  # @line L10
                    parent[tail] = NONE  # @line L10
                    orphans.append(tail)  # @line L10
        while orphans:  # @line L11
            adopt(orphans.popleft())  # @line L11

    source_side = [tree[v] == SRC for v in range(n)]
    edge_flow = [cap[2 * k + 1] for k in range(len(edges))]
    return flow, source_side, edge_flow


def cut_capacity(n: int, edges: Sequence[Tuple[int, int, int]],
                 source_side: Sequence[bool]) -> int:
    """The total capacity of the edges from the source side to the rest."""
    return sum(c for (u, v, c) in edges if source_side[u] and not source_side[v])


def grid_graph(w: int, h: int, terminal_caps, pair_caps) -> Tuple[int, list, int, int]:
    """A 4-connected grid of w x h pixels in the form used in vision.

    terminal_caps[v][u] = (a, b) gives the edges s -> pixel of capacity a and
    pixel -> t of capacity b. pair_caps(u1, v1, u2, v2) gives the capacity of
    each of the two edges between 4-neighbors. Returns (n, edges, s, t).
    """
    s, t = w * h, w * h + 1
    edges = []
    for v in range(h):
        for u in range(w):
            p = v * w + u
            a, b = terminal_caps[v][u]
            if a:
                edges.append((s, p, a))
            if b:
                edges.append((p, t, b))
            for (du, dv) in ((1, 0), (0, 1)):
                uu, vv = u + du, v + dv
                if uu < w and vv < h:
                    q = vv * w + uu
                    c = pair_caps(u, v, uu, vv)
                    if c:
                        edges.append((p, q, c))
                        edges.append((q, p, c))
    return w * h + 2, edges, s, t
test_boykov_kolmogorov_max_flow.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boykov-kolmogorov-max-flow/. The authors are listed in prov/FXPM4P.jsonl.

import itertools
import random
from collections import deque

from boykov_kolmogorov_max_flow import bk_max_flow, cut_capacity, grid_graph


def brute_min_cut(n, edges, s, t):
    """The least cut capacity over all node sets with s and without t."""
    others = [v for v in range(n) if v not in (s, t)]
    best = None
    for bits in itertools.product((False, True), repeat=len(others)):
        side = [False] * n
        side[s] = True
        for v, b in zip(others, bits):
            side[v] = b
        c = cut_capacity(n, edges, side)
        if best is None or c < best:
            best = c
    return best


def edmonds_karp(n, edges, s, t):
    """Reference max flow by shortest augmenting paths."""
    cap = {}
    adj = [set() for _ in range(n)]
    for (u, v, c) in edges:
        cap[(u, v)] = cap.get((u, v), 0) + c
        cap.setdefault((v, u), 0)
        adj[u].add(v)
        adj[v].add(u)
    flow = 0
    while True:
        prev = {s: None}
        queue = deque([s])
        while queue and t not in prev:
            u = queue.popleft()
            for v in adj[u]:
                if v not in prev and cap[(u, v)] > 0:
                    prev[v] = u
                    queue.append(v)
        if t not in prev:
            return flow
        path = []
        v = t
        while prev[v] is not None:
            path.append((prev[v], v))
            v = prev[v]
        delta = min(cap[e] for e in path)
        for (u, v) in path:
            cap[(u, v)] -= delta
            cap[(v, u)] += delta
        flow += delta


def check_flow(n, edges, s, t, value, side, edge_flow):
    assert side[s] and not side[t]
    net = [0] * n
    for (u, v, c), f in zip(edges, edge_flow):
        assert 0 <= f <= c
        net[u] -= f
        net[v] += f
    for v in range(n):
        if v not in (s, t):
            assert net[v] == 0
    assert net[t] == value == -net[s]
    # The cut of the final S tree is saturated, so it is a minimum cut.
    assert cut_capacity(n, edges, side) == value


def random_graph(rng, n, m, cmax):
    edges = []
    for _ in range(m):
        u, v = rng.randrange(n), rng.randrange(n)
        if u != v:
            edges.append((u, v, rng.randint(0, cmax)))
    return edges


def test_small_example():
    # s = 0, a = 1, b = 2, t = 3.
    edges = [(0, 1, 3), (0, 2, 2), (1, 2, 1), (1, 3, 2), (2, 3, 3)]
    value, side, f = bk_max_flow(4, edges, 0, 3)
    assert value == 5
    assert side == [True, False, False, False]
    check_flow(4, edges, 0, 3, value, side, f)


def test_against_brute_force_cuts():
    rng = random.Random(1)
    for _ in range(300):
        n = rng.randint(2, 9)
        edges = random_graph(rng, n, rng.randint(0, 3 * n), 6)
        value, side, f = bk_max_flow(n, edges, 0, n - 1)
        assert value == brute_min_cut(n, edges, 0, n - 1)
        check_flow(n, edges, 0, n - 1, value, side, f)


def test_against_edmonds_karp_on_grids():
    rng = random.Random(2)
    for _ in range(20):
        w, h = rng.randint(2, 9), rng.randint(2, 9)
        tc = [[(rng.choice((0, 0, rng.randint(1, 20))),
                rng.choice((0, 0, rng.randint(1, 20)))) for _ in range(w)]
              for _ in range(h)]
        lam = rng.randint(1, 8)
        n, edges, s, t = grid_graph(w, h, tc, lambda *a: lam)
        value, side, f = bk_max_flow(n, edges, s, t)
        assert value == edmonds_karp(n, edges, s, t)
        check_flow(n, edges, s, t, value, side, f)


def test_parallel_and_antiparallel_edges():
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(3, 7)
        edges = random_graph(rng, n, 4 * n, 4)
        edges += [(u, v, c) for (u, v, c) in edges[: n]]
        edges += [(v, u, c) for (u, v, c) in edges[: n]]
        value, side, f = bk_max_flow(n, edges, n - 1, 0)
        assert value == brute_min_cut(n, edges, n - 1, 0)
        check_flow(n, edges, n - 1, 0, value, side, f)


def test_no_path():
    value, side, f = bk_max_flow(3, [(1, 2, 5), (2, 0, 4)], 0, 2)
    assert value == 0 and side == [True, False, False]

History

Augmenting path methods go back to Ford and Fulkerson (1956), and the strongly polynomial methods of Edmonds and Karp (1972), Dinic (1970) and Goldberg and Tarjan (1988) followed. Greig, Porteous and Seheult (1989) brought minimum cuts to image analysis, and the work of Boykov, Veksler and Zabih (2001) made cuts a standard tool for vision energies. Boykov and Kolmogorov (2004) designed this algorithm for such graphs and published an experimental comparison with Dinic and push-relabel codes. Their code became the default solver in the vision literature and was used in the benchmark of Szeliski et al. (2008).

References

  1. Yuri Boykov and Vladimir Kolmogorov, An experimental comparison of min-cut/max-flow algorithms for energy minimization in vision, IEEE Transactions on Pattern Analysis and Machine Intelligence 26(9), 2004, 1124-1137, Section 3 (the algorithm and the bound O(mn^2|C|)), Section 3.2 (growth, augmentation and adoption stages), Section 3.3 (implementation details), Section 4 (experiments on vision graphs)
  2. Richard Szeliski, Ramin Zabih, Daniel Scharstein, Olga Veksler, Vladimir Kolmogorov, Aseem Agarwala, Marshall Tappen and Carsten Rother, A comparative study of energy minimization methods for Markov random fields with smoothness-based priors, IEEE Transactions on Pattern Analysis and Machine Intelligence 30(6), 2008, 1068-1080, the graph cut methods of the comparison, which use this max-flow code
  3. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Chapter 4, Model fitting and optimization (graph cuts for Markov random fields)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example