-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathford.java
85 lines (74 loc) · 2.01 KB
/
ford.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 ford {
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;
int i,j;
int v;
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) throws java.lang.Exception{
int graph[][] = new int[][]{
{0,8,0,0,3,0},
{0,0,9,0,0,0},
{0,0,0,0,0,2},
{0,0,0,0,0,5},
{0,0,7,4,0,0},
{0,0,0,0,0,0}
};
ford m = new ford();
System.out.println("the maximum flow of the network is "+m.fordfulkerson(graph, 0, 5));
}
}