Ford-Fulkerson
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Ford-Fulkerson is the basic method for maximum flow: keep finding any path with spare capacity and push along it, while allowing earlier decisions to be undone through reverse links. It stops when no such path remains.
Practical use cases
- Web app: Assigning interns to projects. A university portal has interns, each willing to join some projects, and each project has a number of places. Pushing one intern at a time along any free path, and re-routing earlier choices when stuck, fills the maximum number of places.
- Web app: Reassigning support tickets. A helpdesk tool routes tickets to agents by skill. When a new ticket has no free agent, the system can move an earlier ticket to another capable agent, which is the "undo" step, freeing a slot.
- Web app: Sports league elimination check. A league site wants to say whether a team can still reach the top. The question becomes a flow problem over remaining matches, and the answer drives the "eliminated" label.
- System: Network capacity planning. Operators test how much traffic the current links can carry from city A to city B before buying more. The answer tells them whether upgrading a single link would actually raise the total, or whether another link is the real limit.
The story: The Pipe With an Undo Button
Back in the water mohalla, Raju's uncle tried to push as much water as possible to the houses. His method: find any route that still has spare room, and pour as much as the narrowest pipe lets through. Then repeat until no route is left.
It worked nicely on the first few tries. But one day he got a nasty surprise. He had sent water through the little zig-zag pipe in the middle, and afterwards the network looked stuck with only 1 litre delivered. Yet the neighbours swore 2 litres were possible if only the zig-zag pipe were not used.
Mira had the brilliant idea: "What if every pipe came with an undo button?" For a pipe carrying water, imagine a pretend pipe going backwards with the same amount of room. Sending water along the pretend pipe means taking that water back out, so it can go somewhere better. With the undo pipes added (the residual graph), a new route appeared that quietly cancelled the zig-zag litre, and the whole network delivered 2 litres.
That is the Ford-Fulkerson method: repeatedly find an augmenting path in the residual graph (any route with spare room, including undo pipes), push the bottleneck amount, and stop when no such path exists. The flow it ends with is the maximum.
How to spot this problem, and where you need it
A greedy assignment gets stuck with free items on both sides that cannot be paired, but you suspect rearranging earlier choices would allow more matches.
Signs you need it
- You assign things one at a time and later items fail, though a different earlier choice would have worked.
- The problem involves capacities and "at most k" limits per person, room or link.
- It says "maximum number of assignments" or "maximum throughput".
Where to use it in a project
- Assignment screens where each person, room or job has only a limited number of slots.
- Capacity checks in network or logistics tools, such as how many parcels or megabits can flow between two cities.
The solution
Start with zero flow. Search (DFS or BFS) for any path from source to sink along links with remaining room, including reverse links that represent earlier pushes that can be taken back. Push the smallest remaining room along that path, update forward and reverse capacities, and repeat. When no path is found, the flow is the maximum. The reverse links are the undo button that makes this work.
Payoff: Before: a greedy plan placing 17 of 20 interns. After: re-routing earlier choices places all 20.
Explain it like I am 8
You are filling buckets through a maze of tubes. Each time you find any path with space, pour as much as fits. If you get stuck, you may also pour water back out of a tube to try a different way. When nobody can find any path, you have moved the most water possible.
How it works, step by step
- Start with zero flow everywhere. Build the residual graph: for each pipe, room left (capacity − flow), plus an undo pipe of size equal to the flow.
- Find any path from source to sink using pipes with room (a DFS is the simplest way).
- The bottleneck is the smallest room along that path. Push that amount: use up room on the forward pipes and add the same amount of "undo" room on the backward ones.
- Add the pushed amount to the total flow.
- Repeat. When no path exists, the total is the maximum flow.
The code in four languages
PHP
<?php
// Ford-Fulkerson with depth-first search on a matrix of "room left" numbers.
// Returns [max flow, number of rounds].
function fordFulkerson(array $room, int $s, int $t): array {
$n = count($room);
$flow = 0;
$rounds = 0;
// Try to push water from $u to the sink; returns the litres pushed (0 = no route)
$dfs = function (int $u, int $pushed, array &$seen) use (&$dfs, &$room, $t, $n): int {
if ($u === $t) return $pushed;
$seen[$u] = true;
for ($v = 0; $v < $n; $v++) {
if (!$seen[$v] && $room[$u][$v] > 0) {
$got = $dfs($v, min($pushed, $room[$u][$v]), $seen);
if ($got > 0) {
$room[$u][$v] -= $got; // use up room on the pipe
$room[$v][$u] += $got; // add "undo" room backwards
return $got;
}
}
}
return 0;
};
while (true) {
$seen = array_fill(0, $n, false);
$got = $dfs($s, PHP_INT_MAX, $seen);
if ($got === 0) break; // no route left: done
$flow += $got;
$rounds++;
}
return [$flow, $rounds];
}
// nodes: S=0, A=1, B=2, T=3 (the 1-litre pipes from the animation)
$small = [[0,1,1,0],[0,0,1,1],[0,0,0,1],[0,0,0,0]];
[$f, $r] = fordFulkerson($small, 0, 3);
echo 'Small network: flow ' . $f . ' in ' . $r . ' rounds' . PHP_EOL;
// the mohalla network from the Network flow lesson
$mohalla = [[0,3,2,0],[0,0,1,2],[0,0,0,3],[0,0,0,0]];
[$f, $r] = fordFulkerson($mohalla, 0, 3);
echo 'Mohalla network: flow ' . $f . PHP_EOL;JavaScript
// Ford-Fulkerson with depth-first search on a matrix of "room left" numbers.
// Returns [max flow, number of rounds].
function fordFulkerson(capacity, s, t) {
const room = capacity.map(row => row.slice()); // work on a copy
const n = room.length;
let flow = 0;
let rounds = 0;
// Try to push water from u to the sink; returns the litres pushed (0 = no route)
function dfs(u, pushed, seen) {
if (u === t) return pushed;
seen[u] = true;
for (let v = 0; v < n; v++) {
if (!seen[v] && room[u][v] > 0) {
const got = dfs(v, Math.min(pushed, room[u][v]), seen);
if (got > 0) {
room[u][v] -= got; // use up room on the pipe
room[v][u] += got; // add "undo" room backwards
return got;
}
}
}
return 0;
}
while (true) {
const got = dfs(s, Infinity, new Array(n).fill(false));
if (got === 0) break; // no route left: done
flow += got;
rounds++;
}
return [flow, rounds];
}
// nodes: S=0, A=1, B=2, T=3 (the 1-litre pipes from the animation)
const small = [[0,1,1,0],[0,0,1,1],[0,0,0,1],[0,0,0,0]];
let [f, r] = fordFulkerson(small, 0, 3);
console.log('Small network: flow ' + f + ' in ' + r + ' rounds');
// the mohalla network from the Network flow lesson
const mohalla = [[0,3,2,0],[0,0,1,2],[0,0,0,3],[0,0,0,0]];
[f, r] = fordFulkerson(mohalla, 0, 3);
console.log('Mohalla network: flow ' + f);Java
public class Main {
// Try to push water from u to the sink t; returns the litres pushed (0 = no route).
static int dfs(int[][] room, int u, int t, int pushed, boolean[] seen) {
if (u == t) return pushed;
seen[u] = true;
for (int v = 0; v < room.length; v++) {
if (!seen[v] && room[u][v] > 0) {
int got = dfs(room, v, t, Math.min(pushed, room[u][v]), seen);
if (got > 0) {
room[u][v] -= got; // use up room on the pipe
room[v][u] += got; // add "undo" room backwards
return got;
}
}
}
return 0;
}
// Ford-Fulkerson with depth-first search on a matrix of "room left" numbers.
// Returns {max flow, number of rounds}.
static int[] fordFulkerson(int[][] capacity, int s, int t) {
int n = capacity.length;
int[][] room = new int[n][];
for (int i = 0; i < n; i++) room[i] = capacity[i].clone(); // work on a copy
int flow = 0;
int rounds = 0;
while (true) {
int got = dfs(room, s, t, Integer.MAX_VALUE, new boolean[n]);
if (got == 0) break; // no route left: done
flow += got;
rounds++;
}
return new int[]{flow, rounds};
}
public static void main(String[] args) {
// nodes: S=0, A=1, B=2, T=3 (the 1-litre pipes from the animation)
int[][] small = {{0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}};
int[] r = fordFulkerson(small, 0, 3);
System.out.println("Small network: flow " + r[0] + " in " + r[1] + " rounds");
// the mohalla network from the Network flow lesson
int[][] mohalla = {{0, 3, 2, 0}, {0, 0, 1, 2}, {0, 0, 0, 3}, {0, 0, 0, 0}};
r = fordFulkerson(mohalla, 0, 3);
System.out.println("Mohalla network: flow " + r[0]);
}
}Go
package main
import (
"fmt"
"math"
)
// fordFulkerson uses depth-first search on a matrix of "room left" numbers.
// Returns the max flow and the number of rounds.
func fordFulkerson(capacity [][]int, s, t int) (int, int) {
n := len(capacity)
room := make([][]int, n) // work on a copy
for i := range capacity {
room[i] = append([]int(nil), capacity[i]...)
}
flow, rounds := 0, 0
// Try to push water from u to the sink; returns the litres pushed (0 = no route)
var dfs func(u, pushed int, seen []bool) int
dfs = func(u, pushed int, seen []bool) int {
if u == t {
return pushed
}
seen[u] = true
for v := 0; v < n; v++ {
if !seen[v] && room[u][v] > 0 {
got := dfs(v, min(pushed, room[u][v]), seen)
if got > 0 {
room[u][v] -= got // use up room on the pipe
room[v][u] += got // add "undo" room backwards
return got
}
}
}
return 0
}
for {
got := dfs(s, math.MaxInt, make([]bool, n))
if got == 0 {
break // no route left: done
}
flow += got
rounds++
}
return flow, rounds
}
func main() {
// nodes: S=0, A=1, B=2, T=3 (the 1-litre pipes from the animation)
small := [][]int{{0, 1, 1, 0}, {0, 0, 1, 1}, {0, 0, 0, 1}, {0, 0, 0, 0}}
f, r := fordFulkerson(small, 0, 3)
fmt.Printf("Small network: flow %d in %d rounds\n", f, r)
// the mohalla network from the Network flow lesson
mohalla := [][]int{{0, 3, 2, 0}, {0, 0, 1, 2}, {0, 0, 0, 3}, {0, 0, 0, 0}}
f, _ = fordFulkerson(mohalla, 0, 3)
fmt.Println("Mohalla network: flow", f)
}Time: O(E × max flow) with whole-number capacities · Extra space: O(V²) with the matrix. Each round pushes at least one litre, so the number of rounds is bounded by the answer itself; with huge capacities and unlucky paths it can be slow.
Watch out for
- Forgetting the undo (reverse) pipes. Without them a bad early choice can lock the answer below the true maximum.
- Pushing along a path but not updating the room on the backward pipes.
- Using it with non-whole capacities and a careless path choice. The method may not even terminate; Edmonds-Karp (next lesson) fixes that.
Quick check
- What is an "augmenting path"?
- A route from source to sink with spare room (undo pipes allowed)
- The shortest road on the map
- A route that uses every pipe once
- The thickest pipe
- What do the backward "undo" pipes let us do?
- Cancel water we sent earlier so it can take a better route
- Make pipes bigger
- Send water to a new tank
- When does Ford-Fulkerson stop?
- When every pipe is full
- After 10 rounds
- When no route with spare room exists from source to sink