Sub topic 1
What Is a Flow Network?
Many practical questions come down to how much of something can move from one place to another when every link has a limit. Examples include how many litres per second can pass through a pipe system, how many packets per second can cross a network, and how many trucks per day can travel from a factory to a port. A flow network is the mathematical model behind all of these. This chapter defines the model precisely, builds a running example used throughout the tutorial, and covers the representation choices and edge cases that matter once you start writing code.
Prerequisites
This chapter assumes you are comfortable with the following:
- Directed graphs, and storing them as an adjacency matrix or an adjacency list.
- Breadth-first search (BFS). It is used here for a reachability check.
- Big-O notation, used for space and time costs.
- Basic Python: lists, nested lists, loops, functions, and dictionaries.
Later chapters also rely on simple proofs by invariant or contradiction. This chapter needs only careful definitions.
The Parts of a Flow Network
A flow network is a directed graph G = (V, E) with these extra parts:
- A capacity function c that gives every edge (u, v) in E a non-negative number c(u, v). For convenience we set c(u, v) = 0 for any pair that is not an edge.
- A special vertex s called the source, where flow starts.
- A special vertex t called the sink, where flow ends. We require s ≠ t.
We write n = |V| for the number of vertices and m = |E| for the number of edges. Later complexity bounds use the usual V and E for these sizes.
Capacities
A capacity is the maximum amount that can pass along an edge per unit of time. It is fixed in advance and does not change while an algorithm runs. The flow is the quantity that algorithms change: how much actually travels along each edge. Keep these two ideas apart. Capacity is the limit, and flow is what you choose within that limit. The next chapter states the exact rules a flow must obey.
Capacities are directional. If c(u, v) = 5, flow may go from u to v but not from v to u, unless there is also a separate edge (v, u) with its own capacity.
Source and Sink
The source produces flow and the sink absorbs it. Every other vertex is an intermediate vertex that passes flow along. Whatever enters an intermediate vertex must leave it. The source and sink are the only vertices exempt from this rule. The quantity we want to make as large as possible is the net amount leaving s, which equals the net amount arriving at t.
A Running Example
The tutorial uses one six-vertex network throughout. Vertex 0 is the source, vertex 5 is the sink, and vertices 1 to 4 are intermediate.
Notice two things. Edges can point "backwards" relative to the drawing, as with 3 → 2. The capacities leaving s add up to 29, but those entering t add up to only 24. So no flow can be larger than 24, whatever routing you choose. The true maximum for this network is 23. Later chapters show how to compute that number and how to prove that nothing larger is possible.
Representing a Flow Network in Python
The two standard representations are the adjacency matrix and the adjacency list.
| Representation | Space | Find c(u, v) | List the edges leaving u | Parallel edges |
|---|---|---|---|---|
| Adjacency matrix `capacity[u][v]` | O(V²) | O(1) | O(V) | Must be summed into one entry |
| Adjacency list of edge records | O(V + E) | O(degree of u) | O(degree of u) | Stored separately |
The matrix is the simplest choice for small or dense graphs. The first Edmonds-Karp implementation in this tutorial uses it. The list scales to sparse graphs with many vertices, and the later paired-edge implementation uses it.
The code below builds both representations from an edge list. It validates the input and computes the simple upper bound from the previous section. It also uses BFS to check that the sink can be reached at all.
from collections import deque
def build_matrix(n, edges):
"""Build an n x n capacity matrix from (u, v, c) triples."""
capacity = [[0] * n for _ in range(n)]
for u, v, c in edges:
if not (0 <= u < n and 0 <= v < n):
raise ValueError(f"vertex out of range in edge {(u, v)}")
if c < 0:
raise ValueError(f"negative capacity on edge {(u, v)}")
if u == v:
continue # a self-loop can never help move flow from s to t
capacity[u][v] += c # parallel edges merge into one entry
return capacity
def build_list(n, edges):
"""Build an adjacency list: adj[u] is a list of (v, c) pairs."""
adj = [[] for _ in range(n)]
for u, v, c in edges:
if u != v:
adj[u].append((v, c))
return adj
def sink_reachable(capacity, s, t):
"""BFS over edges with positive capacity."""
n = len(capacity)
seen = [False] * n
seen[s] = True
queue = deque([s])
while queue:
u = queue.popleft()
for v in range(n):
if not seen[v] and capacity[u][v] > 0:
seen[v] = True
queue.append(v)
return seen[t]
edges = [
(0, 1, 16), (0, 2, 13),
(1, 3, 12),
(2, 1, 4), (2, 4, 14),
(3, 2, 9), (3, 5, 20),
(4, 3, 7), (4, 5, 4),
]
n, s, t = 6, 0, 5
capacity = build_matrix(n, edges)
adj = build_list(n, edges)
out_of_source = sum(capacity[s])
into_sink = sum(capacity[u][t] for u in range(n))
print("edges leaving 2:", adj[2]) # [(1, 4), (4, 14)]
print("capacity out of s:", out_of_source) # 29
print("capacity into t:", into_sink) # 24
print("upper bound:", min(out_of_source, into_sink)) # 24
print("t reachable:", sink_reachable(capacity, s, t)) # TrueThe capacity matrix built here is exactly the matrix used by the Edmonds-Karp code later in the tutorial.
Edge Cases and Modeling Conventions
Textbooks differ on a few details. Knowing these details helps you avoid surprises when you compare sources or write code.
Antiparallel Edges
Two edges u → v and v → u are called antiparallel. Some textbooks forbid them so that proofs stay tidy. If you need both, they split one edge by adding a new vertex w and replacing u → v with u → w → v, both with the original capacity. The implementations in this tutorial do not need that step. The matrix version keeps both directions in one residual matrix, and the list version gives every edge its own reverse partner. Both compute the correct maximum flow value.
Parallel Edges
Two edges with the same direction between the same pair of vertices behave like one edge whose capacity is the sum of theirs. A matrix can only store them merged, which is why build_matrix uses +=. If you need to report flow per original edge, for example per physical cable, use an adjacency list.
Self-Loops and Irrelevant Vertices
A self-loop u → u never helps move flow from s to t, so you can drop it. A vertex that cannot be reached from s, or that cannot reach t, also carries no useful flow. Keeping these vertices is harmless, but they waste time in each search.
Unlimited Capacity
Some models need an edge with no limit. Use float('inf') or a constant larger than the sum of all finite capacities. A large integer is often safer, because it keeps all arithmetic in integers.
Unreachable Sink
If t cannot be reached from s, the maximum flow is 0. An algorithm handles this correctly without special code, but a quick reachability check like the one above can catch modeling bugs early.
What Comes Next
A flow network only describes what is possible. The next chapter defines a feasible flow, which is an assignment of flow values to edges that respects every capacity and the conservation rule at intermediate vertices. After that, the tutorial builds the residual graph and the augmenting-path methods that find the 23 units hidden in this example.
Exercise
In the running example, add a new edge from vertex 1 directly to t with capacity 10. What is the new simple upper bound min(capacity out of s, capacity into t)? Is it guaranteed to equal the maximum flow?
Show answer
Capacity out of s is still 16 + 13 = 29. Capacity into t becomes 20 + 4 + 10 = 34. The bound is therefore min(29, 34) = 29. It is only an upper bound and is not guaranteed to be reached, because limits inside the network can be tighter. Capacity entering vertices 1 and 3 together is limited, for example. The later chapters on cuts give the exact tool for finding the binding limit.
Exercise
An input file contains the edges (2, 4, 6) and (2, 4, 8) along with the rest of the running example. What does build_matrix store in capacity[2][4]? When would you prefer the adjacency list instead?
Show answer
The original example already contains (2, 4, 14), so build_matrix stores 14 + 6 + 8 = 28. Parallel edges merge by addition. Prefer an adjacency list when you need to report the flow on each original edge separately, or when the graph is large and sparse, so that O(V²) memory is too much.
Exercise
Why do the source and sink have to be exempt from the rule that inflow equals outflow at a vertex?
Show answer
If s and t also had to balance inflow and outflow, no vertex could create or absorb flow. The only valid flows would then be circulations with zero net movement from s to t, and the maximum flow would always be 0. Exempting s and t lets flow start at s and end at t, while every intermediate vertex simply passes it along.