Sub topic 16
Where to Go Next: Dinic and Push-Relabel
Edmonds-Karp has a polynomial worst case, O(V E²), but on dense graphs that bound becomes very large. This chapter covers the two algorithm families most often used in practice instead: Dinic's algorithm and push-relabel. It assumes you already understand residual graphs, augmenting paths, the paired-edge implementation (edge e and its reverse e ^ 1), and the Edmonds-Karp analysis, in particular the fact that BFS distances from the source never decrease.
Why Edmonds-Karp Wastes Work
Each Edmonds-Karp iteration runs a full BFS, which costs O(E), and then uses that BFS for only one path. In the next iteration it runs BFS again, even though the distance labels usually have not changed. The O(V E²) proof shows that the shortest-path distance to the sink can increase at most V times. Between two increases, Edmonds-Karp may run up to E separate BFS passes that all find paths of the same length.
Dinic's algorithm keeps one BFS for all of those same-length paths. Push-relabel goes further and stops searching for whole source-to-sink paths at all.
Dinic's Algorithm
The Level Graph
Dinic runs in phases. Each phase starts with a BFS from the source in the residual graph, which gives every vertex a level, level[v], equal to its BFS distance from s. The level graph keeps only the residual edges u -> v with level[v] == level[u] + 1. Every source-to-sink path in the level graph is therefore a shortest augmenting path.
Blocking Flows
Inside one phase, Dinic finds a blocking flow in the level graph. A blocking flow is a flow after which every s-t path in the level graph contains at least one saturated edge. A blocking flow need not be a maximum flow. It only guarantees that no further shortest path of the current length remains.
After a blocking flow, the distance from s to t in the residual graph strictly increases. This uses the same monotonicity argument as the Edmonds-Karp proof. A distance can only go from 1 up to V − 1, so there are at most V − 1 phases.
The Current-Edge Pointer
The DFS gets its speed from the current-edge pointer, written it[u]. When an edge out of u turns out to be useless, because it is saturated or leads to a dead end, the pointer moves past it, and the DFS never looks at that edge again in this phase. Each edge is skipped at most once per phase. Each successful push saturates at least one edge, and a path has at most V edges. A blocking flow therefore costs O(V E), and the whole algorithm costs O(V² E).
The implementation below reuses the paired-edge layout from the Edmonds-Karp chapter.
from collections import deque
class Dinic:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
self.to = []
self.cap = []
def add_edge(self, u, v, c):
self.graph[u].append(len(self.to))
self.to.append(v)
self.cap.append(c)
self.graph[v].append(len(self.to))
self.to.append(u)
self.cap.append(0)
def bfs(self, s, t):
self.level = [-1] * self.n
self.level[s] = 0
queue = deque([s])
while queue:
u = queue.popleft()
for e in self.graph[u]:
v = self.to[e]
if self.level[v] == -1 and self.cap[e] > 0:
self.level[v] = self.level[u] + 1
queue.append(v)
return self.level[t] != -1
def dfs(self, u, t, pushed):
if u == t:
return pushed
while self.it[u] < len(self.graph[u]):
e = self.graph[u][self.it[u]]
v = self.to[e]
if self.cap[e] > 0 and self.level[v] == self.level[u] + 1:
d = self.dfs(v, t, min(pushed, self.cap[e]))
if d > 0:
self.cap[e] -= d
self.cap[e ^ 1] += d
return d
self.it[u] += 1
return 0
def max_flow(self, s, t):
flow = 0
while self.bfs(s, t):
self.it = [0] * self.n
while True:
pushed = self.dfs(s, t, float('inf'))
if pushed == 0:
break
flow += pushed
return flow
d = Dinic(6)
for u, v, c in [(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)]:
d.add_edge(u, v, c)
print(d.max_flow(0, 5)) # 23The pointer does not advance after a successful push (return d happens before self.it[u] += 1). The edge may still have capacity left, so the next DFS should try it again.
Where Dinic Shines
On unit-capacity networks, where every edge has capacity 1, Dinic runs in O(E · min(V^(2/3), E^(1/2))). On the bipartite matching network from the previous chapter it runs in O(E √V), which is the same bound as the Hopcroft-Karp algorithm. In that setting Hopcroft-Karp is essentially Dinic applied to matching. If you are solving a matching problem with Edmonds-Karp, replacing it with Dinic is a cheap and large improvement.
Push-Relabel
Preflows Instead of Paths
Push-relabel (Goldberg and Tarjan, 1988) gives up on flow conservation while the algorithm runs. It maintains a preflow: every vertex other than s may receive more flow than it sends. The difference is that vertex's excess. A vertex with positive excess is active. The algorithm ends when no vertex is active. At that point the preflow is a valid flow, and it is maximum.
Heights
Each vertex has a height h[v]. The source starts at height V and every other vertex starts at height 0. The algorithm uses two operations:
- Push: if
uis active and the residual edgeu -> vsatisfiesh[u] == h[v] + 1, sendmin(excess[u], residual[u][v])fromutov. - Relabel: if
uis active and has no admissible edge, seth[u]to one more than the smallest height among its residual neighbours.
Think of flow running downhill. When excess gets stuck, the algorithm raises the vertex until the excess can move. Excess that cannot reach the sink eventually rises above height V and drains back to the source.
The code below is a FIFO version on an adjacency matrix. It is short so the logic is easy to follow, and it is not tuned for speed.
from collections import deque
def push_relabel(capacity, s, t):
n = len(capacity)
residual = [row[:] for row in capacity]
height = [0] * n
excess = [0] * n
height[s] = n
for v in range(n):
if residual[s][v] > 0:
c = residual[s][v]
excess[v] += c
excess[s] -= c
residual[v][s] += c
residual[s][v] = 0
active = deque(v for v in range(n) if v not in (s, t) and excess[v] > 0)
while active:
u = active.popleft()
while excess[u] > 0:
pushed = False
for v in range(n):
if residual[u][v] > 0 and height[u] == height[v] + 1:
d = min(excess[u], residual[u][v])
residual[u][v] -= d
residual[v][u] += d
excess[u] -= d
excess[v] += d
if v not in (s, t) and excess[v] == d:
active.append(v)
pushed = True
if excess[u] == 0:
break
if not pushed:
height[u] = 1 + min(height[v] for v in range(n)
if residual[u][v] > 0)
return excess[t]
capacity = [
[0, 16, 13, 0, 0, 0],
[0, 0, 0, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
print(push_relabel(capacity, 0, 5)) # 23The relabel step always finds at least one residual neighbour. Any active vertex has a residual path back to s, because its excess arrived from s and the reverse edges along that route still have capacity.
Bounds and Heuristics
The generic algorithm runs in O(V² E). Processing active vertices in FIFO order gives O(V³), and always choosing the highest active vertex gives O(V² √E). Fast implementations depend on two heuristics:
- Global relabeling occasionally recomputes exact heights with a backward BFS from
t. - The gap heuristic handles a height value that no vertex holds: every vertex above that gap can no longer reach
t, so the algorithm lifts all of them above V at once.
Without these heuristics, push-relabel is often slower than Dinic. With them, it is usually the fastest option on large, dense graphs.
Choosing an Algorithm
| Algorithm | Worst-case time | Best suited for | Main gotcha |
|---|---|---|---|
| Edmonds-Karp | O(V E²) | Teaching, small graphs | Repeats BFS for every path |
| Dinic | O(V² E); O(E √V) on matching | Contest code, unit capacities, matching | Recursion depth in Python |
| FIFO push-relabel | O(V³) | Dense graphs | Slow without global relabel and gap heuristics |
| Highest-label push-relabel | O(V² √E) | Large production instances | More complex to implement correctly |
Push-relabel also leaves you with a minimum cut. In the final residual graph, the vertices that can still reach t form the sink side, which matches the extraction method from earlier chapters. Recovering the actual edge flows from push-relabel takes a second phase that returns leftover excess to the source. The code above skips that phase because it only returns the flow value.
Exercise
In Dinic's DFS, why does the current-edge pointer it[u] advance only when an edge fails, and not after a successful push? What would go wrong with the running time if it[u] were reset to 0 at the start of every DFS call within a phase?
Show answer
After a successful push the edge may still have residual capacity and lead to more flow, so skipping it could stop the phase before it reaches a blocking flow. When an edge fails, it is either saturated or leads only to dead ends at the next level, and neither can change for the rest of the phase, so skipping it permanently is safe. Each edge is then skipped at most once per phase, which bounds one phase at O(V E). If the pointers were reset on every call, each DFS could rescan the same dead edges, and a phase could cost O(E) per push, or O(E²) in total, which gives up the O(V² E) bound.
Exercise
Run the Dinic class on the bipartite matching network from the previous chapter (3 left vertices, 3 right vertices, pairs (0,0), (0,1), (1,0), (2,1), (2,2)). How many phases does it use, and what is the result?
Show answer
The result is 3. Phase 1 has level-graph distance 3 (s, left, right, t) and pushes a blocking flow along disjoint paths, typically matching 2 or 3 pairs depending on edge order. If one left vertex is still unmatched, phase 2 finds a longer augmenting path of length 5 through a reverse edge. Then BFS can no longer reach t, so Dinic uses at most 2 phases that push flow and stops with a flow of 3.