Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Graphs

Push Water Through a Network of Pipes.

Pipes have capacities; how much water can flow from source to sink? Dinic's algorithm is the fast answer: layer the graph by distance from the source with a BFS, then flood all the shortest paths at once with a single DFS “blocking flow,” rebuild the layers, and repeat. Each round the source and sink drift further apart — so it finishes in O(V²E).

O(V²E) · BFS levels + DFS blocking flow · max-flow / min-cut
capacity

Each edge shows flow / cap — how much it carries vs. its limit.

level graph

BFS labels each node with its distance from the source; only next-level edges count.

blocking flow

One DFS saturates every shortest path until none has spare room.

phase

Rebuild the levels and repeat; the sink gets farther each phase, so few phases suffice.

dinic.js — BFS levels, DFS blocking flow, repeat
Ready
A flow network from source s (green) to sink t (purple); edges show flow / capacity. Press Step: first a BFS assigns each node a level (distance from s). Then a DFS pushes flow along level-climbing paths (orange) until each is saturated. Rebuild levels, repeat, until s can't reach t.
0
phase
–
last push
0
max flow

How it works

The basic max-flow idea — find a source-to-sink path with spare capacity, push flow, repeat — can waste time on long, winding paths. Dinic's insight is to always push along shortest paths first, and to do a whole batch of them per BFS. Because the shortest source-to-sink distance strictly grows after each blocking flow, there can be at most V phases.

1

Build the level graph (BFS)

From the source, BFS over edges with spare capacity; each node's level is its hop-distance. If the sink is unreachable, the current flow is maximum — stop.

2

Push a blocking flow (DFS)

DFS from source to sink using only edges from level L to level L+1. Each path pushes its bottleneck capacity; saturated edges drop out.

3

Reuse work per node

An iterator pointer per node skips edges already known to be dead this phase, so the whole blocking flow is found in O(VE) — not one slow DFS per path.

✓

Repeat until disconnected

Rebuild the levels and push again. Distances increase each phase, so after ≤ V phases the sink falls out of the level graph and you have the max flow.

General
O(V²E)
Unit caps
O(E√V)
Bipartite match
O(E√V)
This demo
flow = 19

The code

def max_flow(s, t): flow = 0 while bfs_levels(s, t): # build level graph; stop if t unreachable it = [0] * V # per-node edge iterator while True: pushed = dfs(s, t, INF, it) # one augmenting path in the level graph if pushed == 0: break flow += pushed return flow def dfs(u, t, f, it): if u == t: return f while it[u] < len(g[u]): e = g[u][it[u]] if e.cap - e.flow > 0 and level[e.to] == level[u] + 1: d = dfs(e.to, t, min(f, e.cap - e.flow), it) if d > 0: e.flow += d; e.rev.flow -= d; return d it[u] += 1 # dead edge — skip it next time too return 0

The two-line trick that makes it fast is the shared iterator it[]: once the DFS proves an edge leads nowhere useful this phase, the pointer advances past it and never reconsiders it, so building a blocking flow costs O(VE) total rather than O(E) per path. By the max-flow / min-cut theorem, the value Dinic returns also equals the capacity of the smallest cut separating source from sink — the graph's true bottleneck.

Quick check

1. Why does Dinic build a BFS level graph before pushing flow?

2. What does a "blocking flow" mean within one level graph?

FAQ

What is the maximum-flow problem?

The most that can flow from a source to a sink through capacitated edges, with flow conserved at every other node.

What is a level graph?

A BFS labelling of nodes by distance from the source; Dinic only pushes flow along edges that step from one level to the next.

What is a blocking flow?

A flow in the level graph where every s–t path has a saturated edge, so no more can be pushed without rebuilding the levels.

How fast is it?

O(V²E) in general, O(E√V) on unit-capacity graphs and bipartite matching — much faster than basic Ford–Fulkerson.

The picture: levels decide which edges count

level 0level 1level 2level 3 10/104/104/46/84/94/1010/10 a–c 2: ignoredd–b 6: ignored sabcdt phase 1 pushes 14; the d–b edge matters in phase 2
The page’s demo network after BFS has layered it, with the flow found by phase one written as flow/capacity. Only edges that climb exactly one level are used (accent). The two sideways edges are skipped this phase, which is what keeps every path in the batch a shortest one. They become useful in phase two, once distances change.

Worked example, step by step

Take the page’s network: s→a 10, s→c 10, a→b 4, a→c 2, a→d 8, c→d 9, b→t 10, d→b 6, d→t 10. Edges are tried in that order. Each row is one event: a BFS, or one augmenting path found by the DFS.

StepEventPushedTotal flow
1Phase 1 BFS: levels s0, a1, c1, b2, d2, t3–0
2DFS finds s→a→b→t (bottleneck a→b = 4)44
3DFS finds s→a→d→t (bottleneck: s→a has 6 left)610
4DFS finds s→c→d→t (bottleneck d→t residual 4)414
5DFS returns 0: blocking flow reached, phase 1 over–14
6Phase 2 BFS: levels c1, d2, b3, a3, t4 (via d→b)–14
7DFS finds s→c→d→b→t (bottleneck: c→d has 5 left)519
8Phase 3 BFS: t unreachable, stop–19

Two things show in the trace. First, the sink moved from distance 3 to distance 4 between phases, as the proof requires. The edge d→b was sideways in phase one and a forward step in phase two. Second, the answer is certified without extra work: when the last BFS fails, the vertices it did reach are {s, c}, and the edges leaving that set are s→a (10) and c→d (9). Their capacities add to 19, which equals the flow, so no cut is cheaper and no flow is larger. The whole run took 4 augmenting paths and 3 BFS passes.

Complexity and trade-offs

CaseTimeSpaceWhy
DinicO(V²E)O(V+E)At most V phases, each blocking flow costs O(VE) thanks to the per-node iterator.
Dinic, unit capacitiesO(E√V)O(V+E)The bound that makes bipartite matching fast.
Edmonds–Karp (BFS paths)O(VE²)O(V+E)One BFS per augmenting path instead of one per batch.
Ford–Fulkerson (any DFS path)O(E·F)O(V+E)Depends on the flow value F, not the graph size. On s→a, s→b, a→b, a→t, b→t with 1,000,000 on every edge but a→b (capacity 1), alternating the middle edge needs 2,000,000 paths; Dinic needs 1 phase and 2 paths.
Push–relabel (FIFO)O(V³)O(V+E)No augmenting paths at all; wins on dense graphs.

The bounds are worst cases, and Dinic is usually far under its. The practical lesson is the Ford–Fulkerson row: a bound that depends on the numeric size of the capacities is not a bound you can trust. Shortest paths remove that dependence, and the level graph lets you take many of them for the price of one BFS.

Common mistakes

  • Dropping the level check

    Without level[v] == level[u] + 1, the DFS is plain Ford–Fulkerson and may follow the 1-capacity middle edge back and forth. On the 1,000,000-capacity graph above it needs 2,000,000 augmentations, where the leveled version needs 2.

  • Restarting the edge pointer for each path

    If it[] is reset before every DFS, dead edges are re-scanned each time. On a graph with 300 unit paths through one hub that also has 300 dead-end edges, the shared pointer examines 2,400 edges in the phase and the reset version 316,350. The answer is identical, so only a timer catches it.

  • Forgetting the reverse edges

    Every edge needs a paired capacity-0 reverse edge so that flow can be undone. On the 6-node network [[0,1,1],[0,3,2],[1,2,2],[1,4,1],[2,5,1],[3,2,1],[4,3,1],[4,5,1],[5,1,2],[5,2,2]] (s=0, t=5) the correct maximum is 2, and the version without reverse edges returns 1.

  • Treating an undirected edge as one arc

    An undirected pipe needs capacity in both directions. With s=0, a=1, t=2 and the pipes entered as [[0,1,5],[2,1,5]], the second pipe points the wrong way and the max flow comes out 0. Entering both directions of each pipe returns 5. Add the edge twice, or give its reverse edge the full capacity instead of 0.

  • Recursing on a long path

    The DFS recurses once per level. A 3,000-node chain overflows a recursion limit of 1,000 and raises RecursionError in Python. Use an explicit stack, or raise the limit knowingly.

Where this shows up

  • Bipartite matching

    Add a source joined to every worker and a sink joined to every job, all with capacity 1. The max flow is the size of the largest matching. For workers {j0,j1}, {j0} and {j1,j2} it is 3.

  • Minimum cut and segmentation

    The edges that cross the final cut are the cheapest set to remove to disconnect s from t. Labelling problems such as foreground/background selection are set up so that the cheapest cut is the best labelling.

  • Edge-disjoint paths and network reliability

    With every capacity set to 1, the max flow equals the number of edge-disjoint routes from s to t, i.e. how many links must fail before they are cut off from each other.

  • Scheduling and assignment

    Problems that ask whether supply can meet demand under limits, such as tasks to machines or teams to shifts, become a flow network where the answer is whether the max flow saturates all the demand edges.

SOLVE IT YOURSELF

Solve it: push the most through the network

Ford–Fulkerson finds an augmenting path. Dinic first builds a level graph so it only walks paths that make progress, then saturates all of them at once — turning a potentially unbounded loop into O(V²E). Python or TypeScript.

YOUR TASK

Implement max_flow(n, edges, s, t): given directed [u, v, capacity] edges, return the maximum flow from s to t.

HINTS — 7 IDEAS
  1. Store edges in pairs: a forward edge with its capacity, immediately followed by a reverse edge with capacity 0. Then edge e’s partner is always e ^ 1 — one XOR, no bookkeeping.
  2. The reverse edge is not an optimisation, it is what makes the algorithm correct: pushing flow back along it is how an earlier bad choice gets undone.
  3. Each phase: BFS from s over edges with remaining capacity, labelling every node with its level (distance from the source).
  4. If t is unreachable, the flow is maximal — stop.
  5. Then DFS-blocking-flow, following only edges that go from level L to level L+1. That is what stops the search wandering sideways or backwards.
  6. Keep a per-node cursor across the DFS so a saturated edge is never reconsidered in the same phase — without it the complexity bound falls apart.
  7. Guard s == t before you start. The DFS returns its pushed argument the moment u == t, so with source and sink equal it hands back infinity on the first call and the outer loop never ends — a hang, not a wrong answer.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextMin-Cost Max-Flow: Cheapest Flow First Next on the “Pushing as much as it will take” ladder · rung 2 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms