Max Flow (Ford-Falkerson)

Java code posted by Dmitry
created at 10 Jun 17:47

Edit | Back
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class MaxFlowFordFulkerson {

  static int findPath(int[][] cap, boolean[] vis, int u, int t, int f) {
    if (u == t)
      return f;
    vis[u] = true;
    for (int v = 0; v < vis.length; v++)
      if (!vis[v] && cap[u][v] > 0) {
        int df = findPath(cap, vis, v, t, Math.min(f, cap[u][v]));
        if (df > 0) {
          cap[u][v] -= df;
          cap[v][u] += df;
          return df;
        }
      }
    return 0;
  }

  public static int maxFlow(int[][] cap, int s, int t) {
    for (int flow = 0;;) {
      int df = findPath(cap, new boolean[cap.length], s, t, Integer.MAX_VALUE);
      if (df == 0)
        return flow;
      flow += df;
    }
  }

  // Usage example
  public static void main(String[] args) {
    int[][] capacity = { { 0, 3, 2 }, { 0, 0, 2 }, { 0, 0, 0 } };
    System.out.println(4 == maxFlow(capacity, 0, 2));
  }
}
893 Bytes in 3 ms with coderay