Skip to content

Instantly share code, notes, and snippets.

@skhokhlov
Created January 12, 2016 12:52
Show Gist options
  • Save skhokhlov/c66fd689633492eab8f0 to your computer and use it in GitHub Desktop.
Save skhokhlov/c66fd689633492eab8f0 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
class MaxFlowFordFulkerson {
static int[][] capacity = { { 0, 3, 2 }, { 0, 0, 2 }, { 0, 0, 0 } };
public static int maxFlow(int s, int t) {
for (int flow = 0;;) {
int df = findPath(new boolean[capacity.length], s, t, Integer.MAX_VALUE);
if (df == 0) {
return flow;
}
flow += df;
}
}
static int findPath(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] && capacity[u][v] > 0) {
int df = findPath(vis, v, t, Math.min(f, capacity[u][v]));
if (df > 0) {
capacity[u][v] -= df;
capacity[v][u] += df;
return df;
}
}
}
return 0;
}
public static void main(String[] args) {
System.out.println(maxFlow(0, 2));
System.out.println(Arrays.deepToString(capacity));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment