Network flow
Advanced · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Network flow asks how much of something can be pushed from a source to a destination through links that each have a limit. It models pipes, roads, bandwidth and even assignments, and finds the true maximum.
Practical use cases
- Web app: How much data can the data centre push. An infrastructure page shows servers and links with bandwidth limits. The maximum flow from the upload server to the users tells the team the true ceiling, and the link that is full is the one to upgrade.
- Web app: Matching drivers to riders. A cab app has drivers and riders, with links where a driver is close enough. Treating each link as capacity one and finding the maximum flow gives the largest number of rides that can be matched at once. The same model works for tutors and students, or jobs and workers, since each person has a limit of one match.
- Web app: Seat or slot allocation. A booking site has classes, rooms and slots with limits. Flow finds the biggest set of bookings that respects every limit, and the unmatched ones show what is missing.
- System: Traffic, pipelines and image cuts. City planners test how many cars per hour a road network carries, and image tools use the minimum cut to separate foreground from background. Every use shares the picture of something flowing from a start to an end through limited channels, and the answer is the most that can get through.
The story: Water for the Mohalla
In Mira's mohalla the municipal water tank sat at one end of town and the houses were at the other. Between them ran a tangle of pipes of different sizes: thick mains, thin lanes, and small connecting pipes. Every summer the mohalla argued: "How much water can actually reach us per minute?"
The plumber, Raju's uncle, knew two things. First, a pipe cannot carry more than its size, no matter how hard the tank pushes. Second, a junction is just a meeting point: water that flows in must flow out, since junctions have no tanks of their own.
Mira drew the pipes on paper: the tank, the junctions, the houses, and next to every pipe its size. "Let us send water along any route and watch which pipe fills up first." The thinnest pipe on a route decides how much that route can carry. After filling a few routes, every route from the tank to the houses had at least one full pipe. The total delivered was the answer.
This is a flow network: a directed graph where every edge has a capacity, with a source (the tank) and a sink (the houses). The question "how much can we send?" is the maximum flow problem. It is not only for water: the same idea handles roads, internet traffic and even matching people to jobs.
How to spot this problem, and where you need it
You have a network where each link can carry only so much, and you need to know the largest total amount that can get from one place to another, or the best matching.
Signs you need it
- Each link has a capacity, such as bandwidth, seats, trucks per hour or slots, and the question is "what is the maximum total?".
- A simple greedy assignment leaves some riders, jobs or packets unmatched even though a rearrangement could fit them.
- You want to find the bottleneck, the smallest set of links that limits everything.
Where to use it in a project
- Capacity and bottleneck reports for servers, networks and delivery systems.
- Matching features such as drivers to riders, tutors to students or jobs to workers.
The solution
Model it: a source node, a sink node, and links with capacities. Then repeatedly find a path from source to sink with spare room, push as much as the tightest link allows, and update remaining capacities, including a reverse "undo" capacity. When no path with spare room remains, the total pushed is the maximum, and the full links separating source from sink are the bottleneck.
Payoff: Before: greedy matching placed 82 of 100 riders. After: flow matches 96, and the report names the one overloaded link.
Explain it like I am 8
Imagine a garden hose network where each hose has a different thickness. You pour water in at one end. Water cannot squeeze through more than a hose allows, and nothing leaks or gets stuck in the middle. The most water that can come out at the other end is the maximum flow.
How it works, step by step
- Draw the network: a source (where the water starts), a sink (where it ends) and pipes with capacities.
- Rule 1 (capacity): the flow in a pipe is never more than its size, and never negative.
- Rule 2 (conservation): at every junction except the source and sink, the water in equals the water out.
- The value of a flow is the water leaving the source (equal to the water entering the sink).
- The maximum flow is the biggest value you can get. It equals the capacity of the narrowest "cut" that separates source from sink.
The code in four languages
PHP
<?php
// Check a proposed flow: does it obey the two pipe rules? Returns the flow value, or -1.
// $edges: [from, to, size]; $flows: litres in each pipe (same order)
function checkFlow(array $edges, array $flows, string $source, string $sink): int {
$balance = []; // water in minus water out, per junction
foreach ($edges as $i => [$from, $to, $size]) {
$f = $flows[$i];
if ($f < 0 || $f > $size) return -1; // Rule 1: pipe too small
$balance[$from] = ($balance[$from] ?? 0) - $f;
$balance[$to] = ($balance[$to] ?? 0) + $f;
}
foreach ($balance as $node => $b) {
if ($node === $source || $node === $sink) continue;
if ($b !== 0) return -1; // Rule 2: water appears or vanishes
}
return $balance[$sink]; // litres arriving at the houses
}
$pipes = [['S', 'A', 3], ['S', 'B', 2], ['A', 'B', 1], ['A', 'T', 2], ['B', 'T', 3]];
echo 'Good plan reaches: ' . checkFlow($pipes, [3, 2, 1, 2, 3], 'S', 'T') . PHP_EOL;
echo 'Pipe too small: ' . checkFlow($pipes, [3, 2, 1, 3, 3], 'S', 'T') . PHP_EOL;
echo 'Leaky junction: ' . checkFlow($pipes, [3, 2, 0, 2, 3], 'S', 'T') . PHP_EOL;JavaScript
// Check a proposed flow: does it obey the two pipe rules? Returns the flow value, or -1.
// edges: [from, to, size]; flows: litres in each pipe (same order)
function checkFlow(edges, flows, source, sink) {
const balance = {}; // water in minus water out, per junction
for (let i = 0; i < edges.length; i++) {
const [from, to, size] = edges[i];
const f = flows[i];
if (f < 0 || f > size) return -1; // Rule 1: pipe too small
balance[from] = (balance[from] || 0) - f;
balance[to] = (balance[to] || 0) + f;
}
for (const node in balance) {
if (node === source || node === sink) continue;
if (balance[node] !== 0) return -1; // Rule 2: water appears or vanishes
}
return balance[sink]; // litres arriving at the houses
}
const pipes = [['S', 'A', 3], ['S', 'B', 2], ['A', 'B', 1], ['A', 'T', 2], ['B', 'T', 3]];
console.log('Good plan reaches: ' + checkFlow(pipes, [3, 2, 1, 2, 3], 'S', 'T'));
console.log('Pipe too small: ' + checkFlow(pipes, [3, 2, 1, 3, 3], 'S', 'T'));
console.log('Leaky junction: ' + checkFlow(pipes, [3, 2, 0, 2, 3], 'S', 'T'));Java
import java.util.*;
public class Main {
record Pipe(String from, String to, int size) {}
// Check a proposed flow: does it obey the two pipe rules? Returns the flow value, or -1.
// flows: litres in each pipe (same order as the pipes)
static int checkFlow(List<Pipe> pipes, int[] flows, String source, String sink) {
Map<String, Integer> balance = new HashMap<>(); // water in minus water out, per junction
for (int i = 0; i < pipes.size(); i++) {
Pipe p = pipes.get(i);
int f = flows[i];
if (f < 0 || f > p.size()) return -1; // Rule 1: pipe too small
balance.merge(p.from(), -f, Integer::sum);
balance.merge(p.to(), f, Integer::sum);
}
for (var entry : balance.entrySet()) {
String node = entry.getKey();
if (node.equals(source) || node.equals(sink)) continue;
if (entry.getValue() != 0) return -1; // Rule 2: water appears or vanishes
}
return balance.get(sink); // litres arriving at the houses
}
public static void main(String[] args) {
var pipes = List.of(new Pipe("S", "A", 3), new Pipe("S", "B", 2), new Pipe("A", "B", 1),
new Pipe("A", "T", 2), new Pipe("B", "T", 3));
System.out.println("Good plan reaches: " + checkFlow(pipes, new int[]{3, 2, 1, 2, 3}, "S", "T"));
System.out.println("Pipe too small: " + checkFlow(pipes, new int[]{3, 2, 1, 3, 3}, "S", "T"));
System.out.println("Leaky junction: " + checkFlow(pipes, new int[]{3, 2, 0, 2, 3}, "S", "T"));
}
}Go
package main
import "fmt"
type Pipe struct {
from, to string
size int
}
// checkFlow checks a proposed flow: does it obey the two pipe rules? Returns the flow value, or -1.
// flows: litres in each pipe (same order as the pipes)
func checkFlow(pipes []Pipe, flows []int, source, sink string) int {
balance := map[string]int{} // water in minus water out, per junction
for i, p := range pipes {
f := flows[i]
if f < 0 || f > p.size {
return -1 // Rule 1: pipe too small
}
balance[p.from] -= f
balance[p.to] += f
}
for node, b := range balance {
if node == source || node == sink {
continue
}
if b != 0 {
return -1 // Rule 2: water appears or vanishes
}
}
return balance[sink] // litres arriving at the houses
}
func main() {
pipes := []Pipe{{"S", "A", 3}, {"S", "B", 2}, {"A", "B", 1}, {"A", "T", 2}, {"B", "T", 3}}
fmt.Println("Good plan reaches:", checkFlow(pipes, []int{3, 2, 1, 2, 3}, "S", "T"))
fmt.Println("Pipe too small:", checkFlow(pipes, []int{3, 2, 1, 3, 3}, "S", "T"))
fmt.Println("Leaky junction:", checkFlow(pipes, []int{3, 2, 0, 2, 3}, "S", "T"))
}Time: O(E) to check a flow · Extra space: O(V). Checking a plan is just one pass over the pipes. Finding the best plan needs an algorithm like Ford-Fulkerson (next lessons).
Watch out for
- Forgetting rule 2. A junction in the middle cannot create or swallow water.
- Thinking the answer is the sum of all pipe sizes. The narrowest squeeze between tank and houses decides, not the total.
- Treating pipes as two-way. In a flow network each pipe is directed unless you add a second pipe in the other direction.
Quick check
- A pipe has size 4. Can it carry 5 litres per minute in a valid flow?
- No, flow can never exceed capacity
- Yes, if the next pipe is bigger
- Yes, if the tank is strong
- At a middle junction, 6 litres flow in. How many must flow out?
- More than 6
- Fewer than 6
- Exactly 6
- What decides the maximum flow?
- The number of pipes
- The longest route
- The biggest pipe
- The narrowest cut separating source from sink