Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create MaxFlow Ford Fulkerson #63

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/algo/graph/MaxFlow Ford Fulkerson
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// https://en.wikipedia.org/wiki/Ford–Fulkerson_algorithm in O(V^2 * flow)
public class MaxFlowFordFulkerson {
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;
}
}

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;
}

// 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));
}
}