Skip to content

Instantly share code, notes, and snippets.

@gordinmitya
Created April 28, 2020 20:05
Show Gist options
  • Save gordinmitya/a9f4958e17e0fb2f10103819d6dd8668 to your computer and use it in GitHub Desktop.
Save gordinmitya/a9f4958e17e0fb2f10103819d6dd8668 to your computer and use it in GitHub Desktop.
Ford Fulkerson algorithm
import java.util.ArrayDeque;
import java.util.Queue;
public class Ford {
private static boolean bfs(int[][] residual, int s, int t, int[] path) {
Queue<Integer> queue = new ArrayDeque<>();
boolean[] visited = new boolean[residual.length];
queue.add(s);
visited[s] = true;
while (!queue.isEmpty()) {
int current = queue.poll();
for (int i = 0; i < residual.length; ++i) {
if (visited[i]) continue;
if (residual[current][i] > 0) {
queue.add(i);
visited[i] = true;
path[i] = current;
if (i == t)
return true;
}
}
}
return false;
}
private static int ford(int[][] graph, int source, int sink) {
int maxFlow = 0;
int[][] residual = new int[graph.length][graph.length];
for (int i = 0; i < graph.length; ++i)
System.arraycopy(graph[i], 0, residual[i], 0, graph.length);
int[] path = new int[graph.length];
while (bfs(residual, source, sink, path)) {
int pathFlow = Integer.MAX_VALUE;
int current = sink;
while (current != source) {
int parent = path[current];
pathFlow = Math.min(pathFlow, residual[parent][current]);
current = parent;
}
maxFlow += pathFlow;
current = sink;
while (current != source) {
int parent = path[current];
residual[parent][current] -= pathFlow;
residual[current][parent] += pathFlow;
current = parent;
}
}
return maxFlow;
}
public static void main(String[] args) {
int[][] graph = new int[][]{
//0 1 2 3 4 5 6 7 8 9
{0, 8, 0, 0, 0, 1, 0, 0, 0, 0}, // 0
{0, 0, 7, 0, 0, 0, 0, 0, 0, 0}, // 1
{0, 0, 0, 7, 0, 0, 0, 0, 0, 0}, // 2
{0, 0, 0, 0, 3, 0, 0, 0, 0, 0}, // 3
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // 4
{0, 6, 2, 0, 0, 0, 2, 1, 10, 0}, // 5
{0, 0, 0, 2, 0, 0, 0, 0, 1, 9}, // 6
{0, 0, 0, 0, 0, 0, 0, 0, 4, 0}, // 7
{0, 0, 0, 0, 0, 0, 0, 0, 0, 8}, // 8
{0, 0, 0, 0, 10, 0, 0, 0, 0, 0}, // 9
};
System.out.print(ford(graph, 0, 4));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment