Implementation of Ford Fulkerson (Edmonds-Karp)

Learn how to implement the Ford-Fulkerson method.

In this lesson, we’ll implement the Ford-Fulkerson method to solve maximum flow problems. We’ll select a variant of Ford-Fulkerson called Edmonds-Karp, which has a better worst-case runtime.

Implementation Notes

In principle, we’ll follow the general Ford-Fulkerson method:

  1. Initialize a flow ff of value 00.
  2. Construct the residual network GfG_f.
  3. Try to find an ss-tt-path in GfG_f.
    • If there is such a path, augment the flow ff with it, then go to step 22.
    • If there is no such path, return the flow ff.

Edmonds-Karp’s only addition is that for step 33, a breadth-first search is used to find an ss-tt-path in the residual network.

Our input flow network will be represented using the weighted adjacency list data structure, where the edge weights are the capacities. To simplify the implementation, we won’t explicitly construct the residual network. Instead, we’ll keep track of the flow f(u,v)f(u, v) going through each edge. This is sufficient to compute residual capacities on the fly using the formula

cf(u,v)=c(u,v)f(u,v)+f(v,u).c_f(u, v) = c(u, v) - f(u, v) + f(v, u).

Another technicality is that the residual network Gf=(V,Ef,cf)G_f = (V, E_f, c_f) might contain edges that are not in the original graph. Here is a minimal example:

Get hands-on with 1200+ tech skills courses.