TExcelTAD
Home › Graph Algorithms › Flow Networks

Flow Networks

Water through pipes, packets through a network, goods through a supply chain, cars through a city at rush hour: each moves from a source to a destination through channels of limited capacity. How much can get through per unit of time? That is the maximum-flow problem, and the rest of this course solves it. Besides its literal uses, it models problems that look nothing like plumbing: matching students to projects, scheduling with deadlines, segmenting images, deciding which teams are mathematically eliminated from a league. The DSA course introduces it by example. This lesson gives the precise model.

Definitions

A flow network G=(V,E)G = (V, E) is a directed graph in which every edge (u,v)(u, v) has a non-negative capacity c(u,v)≥0c(u, v) \ge 0. For convenience set c(u,v)=0c(u, v) = 0 when (u,v)∉E(u, v) \notin E. Two vertices are special: a source ss and a sink tt. We assume every vertex lies on some path from ss to tt (other vertices could be deleted), and that the network has no antiparallel edges: if (u,v)∈E(u, v) \in E then (v,u)∉E(v, u) \notin E. Self-loops are excluded too.

A flow is a function f:V×V→Rf : V \times V \to \mathbb{R} with two properties:

  • Capacity constraint: 0≤f(u,v)≤c(u,v)0 \le f(u, v) \le c(u, v) for all u,vu, v. In particular there is no flow where there is no edge.
  • Flow conservation: for every vertex uu other than ss and tt, what flows in flows out:
∑v∈Vf(v,u)=∑v∈Vf(u,v)\sum_{v \in V} f(v, u) = \sum_{v \in V} f(u, v)

The value of a flow is the net flow out of the source:

∣f∣=∑v∈Vf(s,v)−∑v∈Vf(v,s)\lvert f \rvert = \sum_{v \in V} f(s, v) - \sum_{v \in V} f(v, s)

(Here ∣f∣\lvert f \rvert is a value, not an absolute value or a set size.) Usually no edge enters ss, and the second sum is 0. The maximum-flow problem asks for a flow of maximum value.

Checking a flow

The network below is used throughout the section. The program stores a candidate flow next to the capacities, checks both properties and computes the value. A second candidate violates conservation at one vertex, a third a capacity.

python · try it yourself
cap = {("S", "A"): 10, ("S", "B"): 7, ("A", "B"): 4, ("A", "C"): 5, ("B", "D"): 9,
       ("C", "B"): 3, ("C", "T"): 8, ("D", "C"): 4, ("D", "T"): 6}
V = "SABCDT"

def check(flow, s="S", t="T"):
    for e, f in flow.items():
        if e not in cap:
            return f"flow on {e}, which is not an edge"
        if not 0 <= f <= cap[e]:
            return f"capacity violated on {e[0]}->{e[1]}: {f} > {cap[e]}"
    for u in V:
        if u in (s, t):
            continue
        inflow = sum(f for (a, b), f in flow.items() if b == u)
        outflow = sum(f for (a, b), f in flow.items() if a == u)
        if inflow != outflow:
            return f"conservation violated at {u}: in {inflow}, out {outflow}"
    value = sum(f for (a, b), f in flow.items() if a == s) - sum(f for (a, b), f in flow.items() if b == s)
    return f"valid flow of value {value}"

good = {("S", "A"): 7, ("S", "B"): 5, ("A", "B"): 2, ("A", "C"): 5, ("B", "D"): 7,
        ("C", "T"): 6, ("D", "C"): 1, ("D", "T"): 6}
leaky = {**good, ("D", "T"): 5}
greedy = {**good, ("A", "C"): 6, ("S", "A"): 8}
print("candidate 1:", check(good))
print("candidate 2:", check(leaky))
print("candidate 3:", check(greedy))
into_t = sum(f for (a, b), f in good.items() if b == "T")
print("flow arriving at T in candidate 1:", into_t)
candidate 1: valid flow of value 12
candidate 2: conservation violated at D: in 7, out 6
candidate 3: capacity violated on A->C: 6 > 5
flow arriving at T in candidate 1: 12

The value 12 that leaves SS is exactly the amount that arrives at TT. That is no coincidence: conservation at all the other vertices forces it, and the next lesson proves a stronger version, that the net flow across every cut separating ss from tt equals ∣f∣\lvert f \rvert. The best flow for this network has value 14, which the animation finds by Edmonds-Karp, the algorithm of a later lesson:

Two modelling conventions

Antiparallel edges. A road network may have a road in each direction between two junctions, so both (u,v)(u, v) and (v,u)(v, u) are edges. The algorithms of this section assume that does not happen, because they reserve the reverse direction for "undoing" flow. The fix is to split one of the two edges with a new vertex: replace (v,u)(v, u) by (v,x)(v, x) and (x,u)(x, u), both with capacity c(v,u)c(v, u). Any flow in one network corresponds to a flow of the same value in the other.

Several sources and sinks. Factories s1,…,sms_1, \ldots, s_m ship to warehouses t1,…,tnt_1, \ldots, t_n. Add a supersource ss with edges (s,si)(s, s_i) of capacity ∞\infty and a supersink tt with edges (tj,t)(t_j, t) of capacity ∞\infty. A maximum flow from ss to tt is then a maximum flow of the multi-source problem. If a factory can produce at most pip_i units, give (s,si)(s, s_i) capacity pip_i instead.

python · try it yourself
def add_super(cap, sources, sinks, supply=None):
    cap = dict(cap)
    for s in sources:
        cap[("SRC", s)] = supply[s] if supply else float("inf")
    for t in sinks:
        cap[(t, "SNK")] = float("inf")
    return cap

def split_antiparallel(cap):
    cap, n = dict(cap), 0
    for (u, v) in sorted(cap):
        if (v, u) in cap and u < v:                 # keep (u, v), route (v, u) through a new vertex
            n += 1
            x = f"X{n}"
            c = cap.pop((v, u))
            cap[(v, x)] = c
            cap[(x, u)] = c
    return cap

roads = {("P", "Q"): 5, ("Q", "P"): 3, ("Q", "R"): 4, ("R", "Q"): 4, ("P", "R"): 2}
fixed = split_antiparallel(roads)
print("after splitting:", fixed)
print("antiparallel pairs left:", sum((v, u) in fixed for (u, v) in fixed))

plants = {("F1", "H"): 6, ("F2", "H"): 4, ("F2", "W2"): 3, ("H", "W1"): 7, ("H", "W2"): 5}
net = add_super(plants, ["F1", "F2"], ["W1", "W2"], supply={"F1": 5, "F2": 6})
print("with a supersource and a supersink:")
for e, c in sorted(net.items()):
    print(f"  {e[0]:>3} -> {e[1]:<3} capacity {c}")
after splitting: {('P', 'Q'): 5, ('Q', 'R'): 4, ('P', 'R'): 2, ('Q', 'X1'): 3, ('X1', 'P'): 3, ('R', 'X2'): 4, ('X2', 'Q'): 4}
antiparallel pairs left: 0
with a supersource and a supersink:
   F1 -> H   capacity 6
   F2 -> H   capacity 4
   F2 -> W2  capacity 3
    H -> W1  capacity 7
    H -> W2  capacity 5
  SRC -> F1  capacity 5
  SRC -> F2  capacity 6
   W1 -> SNK capacity inf
   W2 -> SNK capacity inf

These two transformations let every algorithm assume one source, one sink and no antiparallel edges. The other usual extension, vertex capacities (a junction that can handle at most kk cars per minute), works the same way: split vertex vv into vinv_{\text{in}} and voutv_{\text{out}} joined by an edge of capacity kk.

Test yourself

Which two properties define a flow?

  1. Acyclicity and connectivity
  2. The capacity constraint and flow conservation at every vertex except the source and the sink
  3. Integrality and minimality
  4. Symmetry and transitivity

A network has edges in both directions between uu and vv. How is it turned into one without antiparallel edges?

  1. Delete one of the edges
  2. Replace (v,u)(v, u) by two edges through a new vertex, both with capacity c(v,u)c(v, u)
  3. Add the capacities into one edge
  4. It cannot be done

How do you model three factories, each with a production limit, shipping to two warehouses?

  1. Run the algorithm three times
  2. Add a supersource with an edge to each factory whose capacity is its limit, and a supersink with infinite-capacity edges from each warehouse
  3. Merge the factories into one vertex
  4. Use a minimum spanning tree