forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EdmondsKarp.java
90 lines (78 loc) · 2.69 KB
/
EdmondsKarp.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.jwetherell.algorithms.graph;
import java.util.ArrayDeque;
import java.util.Queue;
/**
* In computer science, the Edmonds–Karp algorithm is an implementation of the Ford–Fulkerson method for
* computing the maximum flow in a flow network in O(V*E^2) time.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Edmonds%E2%80%93Karp_algorithm">Edmonds-Karp Algorithm (Wikipedia)</a>
* <br>
* @author Mateusz Cianciara <e.cianciara@gmail.com>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
public class EdmondsKarp {
private long[][] flow; //max flow beetween i and j verticles
private long[][] capacity; // edge capacity
private int[] parent; //parent
private boolean[] visited; //just for checking if visited
@SuppressWarnings("unused")
private int n, m;
public EdmondsKarp(int numOfVerticles, int numOfEdges) {
this.n = numOfVerticles;
this.m = numOfEdges;
this.flow = new long[n][n];
this.capacity = new long[n][n];
this.parent = new int[n];
this.visited = new boolean[n];
}
public void addEdge(int from, int to, long capacity) {
assert capacity >= 0;
this.capacity[from][to] += capacity;
}
/**
* Get maximum flow.
*
* @param s source
* @param t target
* @return maximum flow
*/
public long getMaxFlow(int s, int t) {
while (true) {
final Queue<Integer> Q = new ArrayDeque<Integer>();
Q.add(s);
for (int i = 0; i < this.n; ++i)
visited[i] = false;
visited[s] = true;
boolean check = false;
int current;
while (!Q.isEmpty()) {
current = Q.peek();
if (current == t) {
check = true;
break;
}
Q.remove();
for (int i = 0; i < n; ++i) {
if (!visited[i] && capacity[current][i] > flow[current][i]) {
visited[i] = true;
Q.add(i);
parent[i] = current;
}
}
}
if (check == false)
break;
long temp = capacity[parent[t]][t] - flow[parent[t]][t];
for (int i = t; i != s; i = parent[i])
temp = Math.min(temp, (capacity[parent[i]][i] - flow[parent[i]][i]));
for (int i = t; i != s; i = parent[i]) {
flow[parent[i]][i] += temp;
flow[i][parent[i]] -= temp;
}
}
long result = 0;
for (int i = 0; i < n; ++i)
result += flow[s][i];
return result;
}
}