programming-examples/java/Data_Structures/MaxFlowFordFulkersonSimple.java
2019-11-15 12:59:38 +01:00

29 lines
809 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// https://en.wikipedia.org/wiki/FordFulkerson_algorithm in O(V^2 * flow)
public class MaxFlowFordFulkersonSimple {
public static int maxFlow(int[][] cap, int s, int t) {
for (int flow = 0; ; ++flow)
if (!augmentPath(cap, new boolean[cap.length], s, t))
return flow;
}
static boolean augmentPath(int[][] cap, boolean[] vis, int i, int t) {
if (i == t)
return true;
vis[i] = true;
for (int j = 0; j < vis.length; j++)
if (!vis[j] && cap[i][j] > 0 && augmentPath(cap, vis, j, t)) {
--cap[i][j];
++cap[j][i];
return true;
}
return false;
}
// Usage example
public static void main(String[] args) {
int[][] capacity = {{0, 1, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 0}};
System.out.println(2 == maxFlow(capacity, 0, 3));
}
}