-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfordf.java
85 lines (71 loc) · 2.05 KB
/
fordf.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
import java.util.LinkedList;
public class fordf{
static int V = 6;
boolean bfs(int graph[][], int s, int t, int p[]){
boolean visited[] = new boolean[V];
int i;
for(i=0; i<V; i++){
visited[i] = false;
}
int u,v;
LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(s);
visited[s] = true;
p[s] = -1;
while(queue.size()!=0){
u = queue.poll();
for(v=0; v<V; v++){
if(visited[v] == false && graph[u][v]>0){
queue.add(v);
visited[v] = true;
p[v] = u;
}
}
}
if(visited[t] == true){
return true;
}
else{
return false;
}
}
public int fordfulkerson(int graph[][], int s, int t){
int updategraph[][] = new int[V][V];
int u,v;
int i,j;
for(i=0; i<V; i++){
for(j=0; j<V; j++){
updategraph[i][j] = graph[i][j];
}
}
int maxflow = 0;
int parent[] = new int[V];
while(bfs(updategraph, s, t, parent)){
int pathflow = 999;
v=t;
while(v!=s){
u = parent[v];
pathflow = Math.min(pathflow, updategraph[u][v]);
v = parent[v];
}
v=t;
while(v!=s){
u = parent[v];
updategraph[u][v] -= pathflow;
v = parent[v];
}
maxflow += pathflow;
}
return maxflow;
}
public static void main(String args[]){
int graph[][] = new int[][]{
{ 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 },
{ 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 },
{ 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 }
};
fordf f = new fordf();
int max = f.fordfulkerson(graph, 0, 5);
System.out.println("The MaxFlow of the network is = " + max);
}
}