Reading history

Maximum Flow in C: Ford-Fulkerson and Edmonds-Karp

7 min read 0 views

Solve the maximum flow problem in C with Edmonds-Karp: residual graphs, augmenting paths, the max-flow min-cut theorem and bipartite matching.

Imagine water pipes from a reservoir to a city. Each pipe can carry only so many litres per second. What is the most water the city can receive? This is the maximum flow problem. The same model answers questions about traffic, internet bandwidth, and even matching students to jobs. This lesson explains flow networks, residual graphs and augmenting paths, then implements the Edmonds-Karp algorithm and uses the same idea for bipartite matching.

In this lesson you will learn

  • What a flow network, a source and a sink are
  • The two rules every flow must follow
  • Residual capacity and why we add reverse edges
  • The Ford-Fulkerson method and the Edmonds-Karp algorithm
  • The max-flow min-cut theorem
  • Bipartite matching with augmenting paths

You should know BFS and DFS and queues.

Flow Networks

A flow network is a directed graph where each edge has a capacity. Flow starts at the source S and ends at the sink T.

  • Capacity rule: the flow on an edge can never be more than its capacity.
  • Conservation rule: at every vertex except S and T, flow in equals flow out. Nothing is stored or lost.
10/109/100/24/46/89/99/105/610/10SABCDTlabel = flow / capacity; red edges are fullsourcesink

Residual Graphs and Augmenting Paths

The residual capacity of an edge is capacity − flow: how much more it can carry. An augmenting path is a path from S to T where every edge has residual capacity above zero. We can push extra flow along it, equal to its smallest residual capacity (the bottleneck).

There is one more trick. When we push f units along u → v, we also add f units of residual capacity to the reverse edge v → u. This lets a later path undo some earlier flow if that leads to a better total. Without reverse edges, an unlucky early choice could leave us stuck below the maximum.

The Edmonds-Karp Algorithm

The Ford-Fulkerson method keeps finding augmenting paths until none is left. Edmonds-Karp finds each path with BFS, so it always uses a shortest path (fewest edges). This guarantees O(V × E2) time.

#include <stdio.h>
#include <string.h>

#define N 6
static int cap[N][N], flow[N][N];

/* Edmonds-Karp: repeatedly find the SHORTEST augmenting path with BFS */
static int bfs(int s, int t, int *parent) {
    int q[N], head = 0, tail = 0;
    for (int i = 0; i < N; i++) parent[i] = -1;
    parent[s] = s; q[tail++] = s;
    while (head < tail) {
        int u = q[head++];
        for (int v = 0; v < N; v++)
            if (parent[v] == -1 && cap[u][v] - flow[u][v] > 0) {
                parent[v] = u; q[tail++] = v;
                if (v == t) return 1;
            }
    }
    return 0;
}

int main(void) {
    const char *name[N] = {"S", "A", "B", "C", "D", "T"};
    int e[][3] = {{0,1,10},{0,2,10},{1,2,2},{1,3,4},{1,4,8},{2,4,9},{3,5,10},{4,3,6},{4,5,10}};
    for (int i = 0; i < 9; i++) cap[e[i][0]][e[i][1]] = e[i][2];

    int parent[N], total = 0, s = 0, t = 5;
    while (bfs(s, t, parent)) {
        int push = 1 << 30;
        for (int v = t; v != s; v = parent[v]) {          /* bottleneck on the path */
            int r = cap[parent[v]][v] - flow[parent[v]][v];
            if (r < push) push = r;
        }
        printf("path ");
        int path[N], len = 0;
        for (int v = t; v != s; v = parent[v]) path[len++] = v;
        printf("%s", name[s]);
        for (int i = len - 1; i >= 0; i--) printf("->%s", name[path[i]]);
        for (int v = t; v != s; v = parent[v]) {
            flow[parent[v]][v] += push;
            flow[v][parent[v]] -= push;                    /* residual (undo) edge */
        }
        total += push;
        printf("  push %d  (total %d)\n", push, total);
    }
    printf("Maximum flow: %d\n", total);
    return 0;
}

Output

path S->A->C->T  push 4  (total 4)
path S->A->D->T  push 6  (total 10)
path S->B->D->T  push 4  (total 14)
path S->B->D->C->T  push 5  (total 19)
Maximum flow: 19
  • cap[u][v] - flow[u][v] is the residual capacity. Reverse edges start at capacity 0 but can have negative flow, which gives them residual capacity.
  • The BFS records each vertex’s parent, so we can walk back from T to S, find the bottleneck, and update the flows.
  • The first path S→A→C→T is limited by A→C (capacity 4). The last path S→B→D→C→T uses the edge D→C to send flow around the full D→T edge.
  • When BFS finds no more paths, the flow is maximum: 19.

Max-Flow Min-Cut

A cut splits the vertices into a side containing S and a side containing T. Its capacity is the total capacity of edges going from the S side to the T side. Every unit of flow must cross every cut, so no flow can exceed any cut.

The max-flow min-cut theorem says the maximum flow equals the capacity of the smallest cut. Here, the S side {S, A, B, D} gives a cut of A→C (4) + D→C (6) + D→T (10) = 20, but the smallest cut is {S, B} with S→A (10) + B→D (9) = 19, which matches the flow. After the algorithm ends, the vertices still reachable from S in the residual graph form a minimum cut.

Bipartite Matching

Four students each can do some jobs, and each job needs one student. How many students can be given a job? Add a source linked to every student and a sink linked from every job, all with capacity 1. The maximum flow is the largest matching. The code below uses the same augmenting-path idea directly.

#include <stdio.h>
#include <string.h>

/* Maximum bipartite matching as a flow problem:
   each student can do some jobs; each job takes one student. */
#define S 4
#define J 4
static int can[S][J] = {
    {1, 1, 0, 0},    /* Asha:  job 0 or 1 */
    {1, 0, 0, 0},    /* Bilal: job 0 only */
    {0, 1, 1, 0},    /* Chandni: job 1 or 2 */
    {0, 0, 1, 1}     /* Dipu:  job 2 or 3 */
};
static int match_of_job[J], visited[J];

/* Try to find a job for student s, moving other students if needed (augmenting path) */
static int try_assign(int s) {
    for (int j = 0; j < J; j++) {
        if (!can[s][j] || visited[j]) continue;
        visited[j] = 1;
        if (match_of_job[j] == -1 || try_assign(match_of_job[j])) {
            match_of_job[j] = s;
            return 1;
        }
    }
    return 0;
}

int main(void) {
    const char *st[S] = {"Asha", "Bilal", "Chandni", "Dipu"};
    memset(match_of_job, -1, sizeof match_of_job);
    int count = 0;
    for (int s = 0; s < S; s++) {
        memset(visited, 0, sizeof visited);
        if (try_assign(s)) count++;
    }
    printf("Matched %d of %d students:\n", count, S);
    for (int j = 0; j < J; j++)
        if (match_of_job[j] != -1) printf("  job %d -> %s\n", j, st[match_of_job[j]]);
    return 0;
}

Output

Matched 4 of 4 students:
  job 0 -> Bilal
  job 1 -> Asha
  job 2 -> Chandni
  job 3 -> Dipu
  • Asha first takes job 0. When Bilal, who can only do job 0, arrives, try_assign asks Asha to move to job 1. This chain of moves is an augmenting path.
  • Each student is tried once and each search visits each job at most once, so the time is O(students × edges).

Common Mistakes

  1. Leaving out reverse edges, which can stop the algorithm below the true maximum.
  2. Using DFS with real-number capacities; plain Ford-Fulkerson may never finish. BFS (Edmonds-Karp) always does.
  3. Forgetting to update both directions after pushing flow.
  4. Confusing cut capacity with flow; count only edges from the S side to the T side.

Practice Exercises

Exercise 1. A network has edges S→A (5), S→B (3), A→T (2), A→B (4), B→T (6). What is the maximum flow?

Show answer

8. Send 2 along S→A→T, 3 along S→A→B→T and 3 along S→B→T. The cut {S} has capacity 5 + 3 = 8, so no more is possible.

Exercise 2. In the matching example, what happens if Dipu can only do job 2?

Show answer

Chandni and Dipu would both want job 2, and Chandni could move to job 1 only by pushing Asha to job 0, which Bilal holds. Only 3 students can be matched.

Frequently Asked Questions

Are there faster max-flow algorithms?

Yes. Dinic’s algorithm runs in O(V2 × E) and is much faster in practice. Push-relabel algorithms are also widely used. For bipartite matching, Hopcroft–Karp runs in O(E √V).

What if there are several sources or sinks?

Add a “super source” with edges of unlimited capacity to every real source, and a “super sink” fed by every real sink. Then run the usual algorithm.

Summary

  • A flow obeys edge capacities and conserves flow at every inner vertex.
  • Augmenting paths in the residual graph increase the flow; reverse edges allow undoing.
  • Edmonds-Karp uses BFS and runs in O(V × E2).
  • Maximum flow equals the minimum cut, and matching is a special case of flow.

Next: Stack Data Structure in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *