Edmonds-Karp
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Edmonds-Karp is Ford-Fulkerson with one rule: always pick the path with the fewest links using BFS. That single choice guarantees predictable running time instead of occasionally very slow behaviour.
Practical use cases
- Web app: Predictable seat allocation. A booking system assigns passengers to coaches under quota limits. Using BFS to find the path with fewest steps each time means allocation time stays steady, so a rush at midnight does not stall the server.
- Web app: Delivery slot balancing. A grocery app balances orders over drivers and time slots. Short augmenting paths mean few reshuffles of earlier orders, and the plan is quick enough to run when the customer clicks checkout.
- Web app: Capacity check in an admin tool. A back-office tool shows the maximum load a network can take. With Edmonds-Karp the run time depends only on the network size, not on the capacity numbers, so a huge bandwidth number does not make it hang.
- System: Routing, logistics and image segmentation. The same method powers flow computations in routing tools and cuts for separating objects in images. The rule of choosing the path with fewest links each time is what turns a sometimes slow method into one you can safely promise response times for.
The story: Fewest Pipes First
Raju's uncle had a pipe puzzle where two thick pipes carried 100 litres each, but a tiny size-1 connector sat between two junctions. His old method, "find any route with room", sometimes grabbed the zig-zag through the tiny connector and pushed just one litre. Then it needed the undo trick, then another litre, and so on. The mohalla waited and waited, and the tank watched the clock.
"The route you pick matters!" said Mira. "Instead of any route, always pick the one with the fewest pipes." She explained how: start at the tank and spread outwards in ripples, like a stone dropped in a pond. All junctions one pipe away get touched first, then those two pipes away, and so on. The first time the ripple reaches the houses, you have a shortest route.
With that rule the thick-pipe puzzle was solved in two rounds: 100 litres along the two-pipe route through A, then 100 litres along the two-pipe route through B. The zig-zag route with three pipes never got picked while shorter ones had room.
This is the Edmonds-Karp algorithm: Ford-Fulkerson where the route is always found with BFS. It is no cleverer in the pushing; it simply chooses routes wisely, which guarantees the number of rounds depends only on the shape of the network, not on how big the capacities are.
How to spot this problem, and where you need it
You are using a flow method that sometimes becomes very slow on certain capacity numbers, and you want a version that runs in steady, predictable time.
Signs you need it
- A flow implementation using DFS works on tests but occasionally takes ages with large capacity values.
- You need a dependable method for a user-facing feature where waiting is not acceptable.
- The problem is a standard maximum flow or matching with moderate size.
Where to use it in a project
- Seat, slot or driver allocation in booking and delivery systems.
- Back-office capacity checks that must finish within a set time.
The solution
Run the same loop as Ford-Fulkerson, but find each augmenting path with BFS from source to sink on the residual network (links with spare room, including reverse links). BFS yields the path with fewest links. Push the bottleneck amount along it, update capacities, and repeat until BFS cannot reach the sink. Fewest-link paths limit how many rounds are needed to a count based only on graph size.
Payoff: Before: a run that took 30 seconds on odd capacity values. After: a steady well under a second whatever the numbers.
Explain it like I am 8
When you need to get water to the houses, choose the route with the fewest pipe pieces first. It is like choosing the shortest line at the chai stall: fewer steps, fewer surprises, and the job is done in a small, predictable number of rounds.
How it works, step by step
- Keep the residual graph exactly as in Ford-Fulkerson (spare room plus undo pipes).
- Run a BFS from the source, only crossing pipes with room left. Remember each junction's parent.
- If the BFS never reaches the sink, stop: the flow is maximum.
- Otherwise walk back from the sink using the parents to get the shortest route. Its bottleneck is the smallest room on it.
- Push the bottleneck amount (reduce room forward, increase undo room backward), add it to the total, and repeat.
The code in four languages
PHP
<?php
// Edmonds-Karp: Ford-Fulkerson, but always the route with the FEWEST pipes (BFS).
// Returns [max flow, number of rounds].
function edmondsKarp(array $room, int $s, int $t): array {
$n = count($room);
$flow = 0;
$rounds = 0;
while (true) {
// BFS: ripples spreading out from the tank
$parent = array_fill(0, $n, -1);
$parent[$s] = $s;
$queue = [$s];
for ($h = 0; $h < count($queue) && $parent[$t] === -1; $h++) {
$u = $queue[$h];
for ($v = 0; $v < $n; $v++) {
if ($parent[$v] === -1 && $room[$u][$v] > 0) {
$parent[$v] = $u;
$queue[] = $v;
}
}
}
if ($parent[$t] === -1) break; // the ripple never reached the houses
$push = PHP_INT_MAX; // bottleneck along the shortest route
for ($v = $t; $v !== $s; $v = $parent[$v]) {
$push = min($push, $room[$parent[$v]][$v]);
}
for ($v = $t; $v !== $s; $v = $parent[$v]) {
$room[$parent[$v]][$v] -= $push; // use up room
$room[$v][$parent[$v]] += $push; // add undo room
}
$flow += $push;
$rounds++;
}
return [$flow, $rounds];
}
// S=0, A=1, B=2, T=3 with big pipes (100) and a tiny middle pipe (1)
$big = [[0,100,100,0],[0,0,1,100],[0,0,0,100],[0,0,0,0]];
[$f, $r] = edmondsKarp($big, 0, 3);
echo 'Big-pipe network: flow ' . $f . ' in ' . $r . ' rounds' . PHP_EOL;
$mohalla = [[0,3,2,0],[0,0,1,2],[0,0,0,3],[0,0,0,0]];
[$f, $r] = edmondsKarp($mohalla, 0, 3);
echo 'Mohalla network: flow ' . $f . ' in ' . $r . ' rounds' . PHP_EOL;JavaScript
// Edmonds-Karp: Ford-Fulkerson, but always the route with the FEWEST pipes (BFS).
// Returns [max flow, number of rounds].
function edmondsKarp(capacity, s, t) {
const room = capacity.map(row => row.slice()); // work on a copy
const n = room.length;
let flow = 0;
let rounds = 0;
while (true) {
// BFS: ripples spreading out from the tank
const parent = new Array(n).fill(-1);
parent[s] = s;
const queue = [s];
for (let h = 0; h < queue.length && parent[t] === -1; h++) {
const u = queue[h];
for (let v = 0; v < n; v++) {
if (parent[v] === -1 && room[u][v] > 0) {
parent[v] = u;
queue.push(v);
}
}
}
if (parent[t] === -1) break; // the ripple never reached the houses
let push = Infinity; // bottleneck along the shortest route
for (let v = t; v !== s; v = parent[v]) {
push = Math.min(push, room[parent[v]][v]);
}
for (let v = t; v !== s; v = parent[v]) {
room[parent[v]][v] -= push; // use up room
room[v][parent[v]] += push; // add undo room
}
flow += push;
rounds++;
}
return [flow, rounds];
}
// S=0, A=1, B=2, T=3 with big pipes (100) and a tiny middle pipe (1)
const big = [[0,100,100,0],[0,0,1,100],[0,0,0,100],[0,0,0,0]];
let [f, r] = edmondsKarp(big, 0, 3);
console.log('Big-pipe network: flow ' + f + ' in ' + r + ' rounds');
const mohalla = [[0,3,2,0],[0,0,1,2],[0,0,0,3],[0,0,0,0]];
[f, r] = edmondsKarp(mohalla, 0, 3);
console.log('Mohalla network: flow ' + f + ' in ' + r + ' rounds');Java
import java.util.*;
public class Main {
// Edmonds-Karp: Ford-Fulkerson, but always the route with the FEWEST pipes (BFS).
// Returns {max flow, number of rounds}.
static int[] edmondsKarp(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) {
// BFS: ripples spreading out from the tank
int[] parent = new int[n];
Arrays.fill(parent, -1);
parent[s] = s;
Deque<Integer> queue = new ArrayDeque<>();
queue.add(s);
while (!queue.isEmpty() && parent[t] == -1) {
int u = queue.poll();
for (int v = 0; v < n; v++) {
if (parent[v] == -1 && room[u][v] > 0) {
parent[v] = u;
queue.add(v);
}
}
}
if (parent[t] == -1) break; // the ripple never reached the houses
int push = Integer.MAX_VALUE; // bottleneck along the shortest route
for (int v = t; v != s; v = parent[v]) {
push = Math.min(push, room[parent[v]][v]);
}
for (int v = t; v != s; v = parent[v]) {
room[parent[v]][v] -= push; // use up room
room[v][parent[v]] += push; // add undo room
}
flow += push;
rounds++;
}
return new int[]{flow, rounds};
}
public static void main(String[] args) {
// S=0, A=1, B=2, T=3 with big pipes (100) and a tiny middle pipe (1)
int[][] big = {{0, 100, 100, 0}, {0, 0, 1, 100}, {0, 0, 0, 100}, {0, 0, 0, 0}};
int[] r = edmondsKarp(big, 0, 3);
System.out.println("Big-pipe network: flow " + r[0] + " in " + r[1] + " rounds");
int[][] mohalla = {{0, 3, 2, 0}, {0, 0, 1, 2}, {0, 0, 0, 3}, {0, 0, 0, 0}};
r = edmondsKarp(mohalla, 0, 3);
System.out.println("Mohalla network: flow " + r[0] + " in " + r[1] + " rounds");
}
}Go
package main
import (
"fmt"
"math"
)
// edmondsKarp is Ford-Fulkerson, but always the route with the FEWEST pipes (BFS).
// Returns the max flow and the number of rounds.
func edmondsKarp(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
for {
// BFS: ripples spreading out from the tank
parent := make([]int, n)
for i := range parent {
parent[i] = -1
}
parent[s] = s
queue := []int{s}
for h := 0; h < len(queue) && parent[t] == -1; h++ {
u := queue[h]
for v := 0; v < n; v++ {
if parent[v] == -1 && room[u][v] > 0 {
parent[v] = u
queue = append(queue, v)
}
}
}
if parent[t] == -1 {
break // the ripple never reached the houses
}
push := math.MaxInt // bottleneck along the shortest route
for v := t; v != s; v = parent[v] {
push = min(push, room[parent[v]][v])
}
for v := t; v != s; v = parent[v] {
room[parent[v]][v] -= push // use up room
room[v][parent[v]] += push // add undo room
}
flow += push
rounds++
}
return flow, rounds
}
func main() {
// S=0, A=1, B=2, T=3 with big pipes (100) and a tiny middle pipe (1)
big := [][]int{{0, 100, 100, 0}, {0, 0, 1, 100}, {0, 0, 0, 100}, {0, 0, 0, 0}}
f, r := edmondsKarp(big, 0, 3)
fmt.Printf("Big-pipe network: flow %d in %d rounds\n", f, r)
mohalla := [][]int{{0, 3, 2, 0}, {0, 0, 1, 2}, {0, 0, 0, 3}, {0, 0, 0, 0}}
f, r = edmondsKarp(mohalla, 0, 3)
fmt.Printf("Mohalla network: flow %d in %d rounds\n", f, r)
}Time: O(V × E²) · Extra space: O(V²) with the matrix. The number of rounds is bounded by pipes times junctions, whatever the pipe sizes are; each round costs one BFS.
Watch out for
- Using DFS instead of BFS and still calling it Edmonds-Karp. The shortest-route choice is the whole point.
- Forgetting to update the undo (reverse) room after pushing.
- Finding the route but computing the bottleneck on the wrong pipes. Walk the parent links from the sink back to the source.
Quick check
- What is the difference between Edmonds-Karp and Ford-Fulkerson?
- Edmonds-Karp ignores undo pipes
- Edmonds-Karp works only on trees
- Edmonds-Karp always uses the route with the fewest pipes (BFS)
- Why is choosing the shortest route good?
- It uses less water
- The number of rounds no longer depends on the pipe sizes
- It avoids all bottlenecks
- The BFS cannot reach the houses using pipes with room. What now?
- Stop: the current flow is the maximum
- Start again from the beginning
- Push 1 litre anyway