Edmonds-Karp
Time O(V × E²) Space O(V²)Capacity matrix (parallel edges add up). BFS for a path with positive residual capacity, push its bottleneck, update both directions.
n = 4, edges = [[0,1,3],[0,2,2],[1,2,1],[1,3,2],[2,3,3]], s = 0, t = 3flow(vars)
Step 1/5This example is already small (4 nodes), so we trace it in full. Edge labels show flow/capacity. Push water from 0 to 3.
import java.util.*;
class Solution {
public int maxFlow(int n, int[][] edges, int s, int t) {
int[][] cap = new int[n][n];
for (int[] e : edges) cap[e[0]][e[1]] += e[2];
int flow = 0;
while (true) {
int[] parent = new int[n];
Arrays.fill(parent, -1);
parent[s] = s;
Deque<Integer> q = new ArrayDeque<>();
q.offer(s);
while (!q.isEmpty() && parent[t] == -1) {
int u = q.poll();
for (int v = 0; v < n; v++)
if (parent[v] == -1 && cap[u][v] > 0) { parent[v] = u; q.offer(v); }
}
if (parent[t] == -1) return flow;
int push = Integer.MAX_VALUE;
for (int v = t; v != s; v = parent[v]) push = Math.min(push, cap[parent[v]][v]);
for (int v = t; v != s; v = parent[v]) { cap[parent[v]][v] -= push; cap[v][parent[v]] += push; }
flow += push;
}
}
}Verdict: Shortest augmenting paths guarantee termination.