AlgoTales · Roadmap

Dinic

Advanced · 13 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Dinic's algorithm speeds up maximum flow by sorting nodes into levels with BFS, then pushing as much as possible through all shortest paths at once with DFS. It handles large matching and capacity problems far faster.

Practical use cases

  • Web app: Matching thousands of drivers to riders. A ride-hailing back end must pair many drivers and riders every few seconds. Level-based pushing handles many pairings per round, instead of one path at a time, so a rush-hour batch finishes fast.
  • Web app: Bulk interview scheduling. A hiring platform books 5,000 candidates into limited interviewer slots. Dinic computes the biggest possible set of bookings quickly, so recruiters see the plan in seconds.
  • Web app: Large capacity report. A cloud dashboard models thousands of links. Dinic gives the maximum throughput report while the page loads, instead of an overnight job. The team can try "what if we add a link?" and see the effect.
  • System: Contests and computer vision. Programming contests use Dinic as the standard fast flow, and image tools use it to cut pictures into regions. The common thread is large input: Dinic sorts nodes into levels first, then pushes along many shortest paths together, rather than one path at a time.

The story: The Pipe Levels of Chowk Nagar

The water network of Chowk Nagar had grown big: dozens of junctions and pipes. Raju's uncle used Edmonds-Karp, but he found it wasteful. "Each time I find one shortest route, push water, and then start a fresh ripple search. The shape of the network barely changes between searches, yet I re-do everything."

Mira had a better plan. "Do the ripple search once and label every junction with its level: how many pipes it is from the tank. Then, in this round, only use pipes that go one level further out. Inside that layered picture, push as many routes as you can find, one after another, until every route is blocked."

Because the water only ever travels level by level, there are no loops or sideways wandering, and a quick depth-first search with a little memory ("this junction is a dead end, do not try it again") finds route after route cheaply. When no more routes remain in the layers, the shortest distance from the tank to the houses must have grown. Do another ripple search, relabel the levels, and repeat.

This is Dinic's algorithm: BFS to build a level graph, then DFS to push a "blocking flow" through it, round after round. It needs far fewer BFS passes than Edmonds-Karp and is a favourite in programming contests.

How to spot this problem, and where you need it

Your flow or matching problem is large, so pushing one path at a time is too slow, and you need to move lots of flow per round.

Signs you need it

  • You have thousands of nodes or tens of thousands of links and Edmonds-Karp takes too long.
  • The network is layered or has mostly unit capacities, as in matching problems.
  • You see contest-style limits and wording like "maximum matching" on big input.

Where to use it in a project

  • Large-scale matching in ride, delivery and hiring platforms.
  • Heavy capacity or image-segmentation jobs where speed matters.

The solution

Repeat in phases. Phase start: run BFS from the source to give every node a level (its fewest-step distance). Then run DFS that only goes from a level to the next higher level, pushing flow along all such paths until every one is blocked, using a pointer per node so dead ends are not retried. When the sink can no longer be reached by BFS, the flow is the maximum.

Payoff: Before: matching 20,000 riders path by path took a minute. After: level-by-level pushing finishes in a couple of seconds.

Explain it like I am 8

Sort your friends into rows by how far they stand from the water tank. Water may only move to the very next row. Pour as much as you can through all the little rows paths until every path is blocked. Then rearrange the rows and try again until the houses can no longer be reached.

How it works, step by step

  1. Run a BFS from the source over pipes with room left. Each junction gets a level. If the sink gets no level, you are done.
  2. Only pipes that lead from level L to level L + 1 with room left may be used this round: the level graph.
  3. Use a DFS to find a route in the level graph, push its bottleneck, and update the room (and undo room).
  4. Keep a pointer per junction so a pipe that is full or leads to a dead end is never tried again in this round. Repeat until the DFS finds nothing (a "blocking flow").
  5. Go back to step 1 and rebuild the levels. Stop when the sink is unreachable. The total pushed is the maximum flow.

The code in four languages

PHP

<?php
// Dinic's algorithm: BFS builds levels, DFS pushes a "blocking flow" through them.
function dinic(int $n, array $pipes, int $s, int $t): int {
    $to = []; $room = []; $g = array_fill(0, $n, []);
    foreach ($pipes as [$u, $v, $size]) {
        $g[$u][] = count($to); $to[] = $v; $room[] = $size;   // forward pipe
        $g[$v][] = count($to); $to[] = $u; $room[] = 0;       // undo pipe (partner is id ^ 1)
    }
    $flow = 0;
    while (true) {
        // Round: BFS to give every junction a level
        $level = array_fill(0, $n, -1);
        $level[$s] = 0;
        $queue = [$s];
        for ($h = 0; $h < count($queue); $h++) {
            $u = $queue[$h];
            foreach ($g[$u] as $e) {
                if ($room[$e] > 0 && $level[$to[$e]] < 0) {
                    $level[$to[$e]] = $level[$u] + 1;
                    $queue[] = $to[$e];
                }
            }
        }
        if ($level[$t] < 0) break;                            // houses unreachable: finished

        $next = array_fill(0, $n, 0);                         // pointer: next pipe to try per junction
        $dfs = function (int $u, int $pushed) use (&$dfs, &$room, &$next, $g, $to, $level, $t): int {
            if ($u === $t) return $pushed;
            for (; $next[$u] < count($g[$u]); $next[$u]++) {
                $e = $g[$u][$next[$u]];
                $v = $to[$e];
                if ($room[$e] > 0 && $level[$v] === $level[$u] + 1) {   // only one level further
                    $got = $dfs($v, min($pushed, $room[$e]));
                    if ($got > 0) {
                        $room[$e] -= $got;
                        $room[$e ^ 1] += $got;
                        return $got;
                    }
                }
            }
            return 0;
        };
        while (($got = $dfs($s, PHP_INT_MAX)) > 0) $flow += $got;   // blocking flow
    }
    return $flow;
}

// S=0 A=1 B=2 C=3 D=4 T=5, pipes [from, to, size]
$pipes = [[0,1,10],[0,2,10],[1,3,4],[1,4,8],[2,4,9],[3,5,10],[4,3,6],[4,5,10]];
echo 'Maximum flow: ' . dinic(6, $pipes, 0, 5) . PHP_EOL;

JavaScript

// Dinic's algorithm: BFS builds levels, DFS pushes a "blocking flow" through them.
function dinic(n, pipes, s, t) {
  const to = [], room = [];
  const g = Array.from({ length: n }, () => []);
  for (const [u, v, size] of pipes) {
    g[u].push(to.length); to.push(v); room.push(size);   // forward pipe
    g[v].push(to.length); to.push(u); room.push(0);      // undo pipe (partner is id ^ 1)
  }
  let flow = 0;
  while (true) {
    // Round: BFS to give every junction a level
    const level = new Array(n).fill(-1);
    level[s] = 0;
    const queue = [s];
    for (let h = 0; h < queue.length; h++) {
      const u = queue[h];
      for (const e of g[u]) {
        if (room[e] > 0 && level[to[e]] < 0) {
          level[to[e]] = level[u] + 1;
          queue.push(to[e]);
        }
      }
    }
    if (level[t] < 0) break;                             // houses unreachable: finished

    const next = new Array(n).fill(0);                   // pointer: next pipe to try per junction
    const dfs = (u, pushed) => {
      if (u === t) return pushed;
      for (; next[u] < g[u].length; next[u]++) {
        const e = g[u][next[u]];
        const v = to[e];
        if (room[e] > 0 && level[v] === level[u] + 1) {  // only one level further
          const got = dfs(v, Math.min(pushed, room[e]));
          if (got > 0) {
            room[e] -= got;
            room[e ^ 1] += got;
            return got;
          }
        }
      }
      return 0;
    };
    let got;
    while ((got = dfs(s, Infinity)) > 0) flow += got;    // blocking flow
  }
  return flow;
}

// S=0 A=1 B=2 C=3 D=4 T=5, pipes [from, to, size]
const pipes = [[0,1,10],[0,2,10],[1,3,4],[1,4,8],[2,4,9],[3,5,10],[4,3,6],[4,5,10]];
console.log('Maximum flow: ' + dinic(6, pipes, 0, 5));

Java

import java.util.*;

public class Main {
    static List<Integer> to = new ArrayList<>();
    static List<Integer> room = new ArrayList<>();
    static List<List<Integer>> g = new ArrayList<>();
    static int[] level, next;

    static void addPipe(int u, int v, int size) {
        g.get(u).add(to.size()); to.add(v); room.add(size);   // forward pipe
        g.get(v).add(to.size()); to.add(u); room.add(0);      // undo pipe (partner is id ^ 1)
    }

    // DFS pushes water only one level further each step.
    static int dfs(int u, int t, int pushed) {
        if (u == t) return pushed;
        for (; next[u] < g.get(u).size(); next[u]++) {        // pointer: next pipe to try
            int e = g.get(u).get(next[u]);
            int v = to.get(e);
            if (room.get(e) > 0 && level[v] == level[u] + 1) {
                int got = dfs(v, t, Math.min(pushed, room.get(e)));
                if (got > 0) {
                    room.set(e, room.get(e) - got);
                    room.set(e ^ 1, room.get(e ^ 1) + got);
                    return got;
                }
            }
        }
        return 0;
    }

    // Dinic's algorithm: BFS builds levels, DFS pushes a "blocking flow" through them.
    static int dinic(int n, int[][] pipes, int s, int t) {
        for (int i = 0; i < n; i++) g.add(new ArrayList<>());
        for (int[] p : pipes) addPipe(p[0], p[1], p[2]);
        int flow = 0;
        while (true) {
            // Round: BFS to give every junction a level
            level = new int[n];
            Arrays.fill(level, -1);
            level[s] = 0;
            Deque<Integer> queue = new ArrayDeque<>();
            queue.add(s);
            while (!queue.isEmpty()) {
                int u = queue.poll();
                for (int e : g.get(u)) {
                    if (room.get(e) > 0 && level[to.get(e)] < 0) {
                        level[to.get(e)] = level[u] + 1;
                        queue.add(to.get(e));
                    }
                }
            }
            if (level[t] < 0) break;                          // houses unreachable: finished

            next = new int[n];
            int got;
            while ((got = dfs(s, t, Integer.MAX_VALUE)) > 0) flow += got;   // blocking flow
        }
        return flow;
    }

    public static void main(String[] args) {
        // S=0 A=1 B=2 C=3 D=4 T=5, pipes {from, to, size}
        int[][] pipes = {{0, 1, 10}, {0, 2, 10}, {1, 3, 4}, {1, 4, 8}, {2, 4, 9}, {3, 5, 10}, {4, 3, 6}, {4, 5, 10}};
        System.out.println("Maximum flow: " + dinic(6, pipes, 0, 5));
    }
}

Go

package main

import (
	"fmt"
	"math"
)

// dinic: BFS builds levels, DFS pushes a "blocking flow" through them.
func dinic(n int, pipes [][3]int, s, t int) int {
	var to, room []int
	g := make([][]int, n)
	for _, p := range pipes {
		u, v, size := p[0], p[1], p[2]
		g[u] = append(g[u], len(to))
		to, room = append(to, v), append(room, size) // forward pipe
		g[v] = append(g[v], len(to))
		to, room = append(to, u), append(room, 0) // undo pipe (partner is id ^ 1)
	}
	flow := 0
	for {
		// Round: BFS to give every junction a level
		level := make([]int, n)
		for i := range level {
			level[i] = -1
		}
		level[s] = 0
		queue := []int{s}
		for h := 0; h < len(queue); h++ {
			u := queue[h]
			for _, e := range g[u] {
				if room[e] > 0 && level[to[e]] < 0 {
					level[to[e]] = level[u] + 1
					queue = append(queue, to[e])
				}
			}
		}
		if level[t] < 0 {
			break // houses unreachable: finished
		}

		next := make([]int, n) // pointer: next pipe to try per junction
		var dfs func(u, pushed int) int
		dfs = func(u, pushed int) int {
			if u == t {
				return pushed
			}
			for ; next[u] < len(g[u]); next[u]++ {
				e := g[u][next[u]]
				v := to[e]
				if room[e] > 0 && level[v] == level[u]+1 { // only one level further
					if got := dfs(v, min(pushed, room[e])); got > 0 {
						room[e] -= got
						room[e^1] += got
						return got
					}
				}
			}
			return 0
		}
		for got := dfs(s, math.MaxInt); got > 0; got = dfs(s, math.MaxInt) {
			flow += got // blocking flow
		}
	}
	return flow
}

func main() {
	// S=0 A=1 B=2 C=3 D=4 T=5, pipes [from, to, size]
	pipes := [][3]int{{0, 1, 10}, {0, 2, 10}, {1, 3, 4}, {1, 4, 8}, {2, 4, 9}, {3, 5, 10}, {4, 3, 6}, {4, 5, 10}}
	fmt.Println("Maximum flow:", dinic(6, pipes, 0, 5))
}

Time: O(V² × E) · Extra space: O(V + E). At most V rounds, each costing a BFS plus a blocking flow. It is much faster in practice, and very fast on unit-size pipes.

Watch out for

  • Forgetting the per-junction pointer. Without it the DFS keeps retrying pipes that already failed and the round becomes very slow.
  • Allowing pipes that stay on the same level or go back a level. Only level + 1 pipes belong to the level graph.
  • Not rebuilding the levels after each blocking flow. The levels are only valid for the current round.

Quick check

  1. What is a "level" in Dinic's algorithm?
    • How many pipes a junction is from the source (using pipes with room)
    • The junction's number
    • The pipe's thickness
  2. Which pipes can the DFS use during a round?
    • Any pipe with room
    • Only the thickest pipes
    • Pipes that lead exactly one level further out and have room
  3. When does Dinic stop?
    • When every pipe is full
    • After the first blocking flow
    • When the BFS cannot reach the sink
    • When all levels are equal