Skip to content

Commit 97ea982

Browse files
committed
Ford-Fulkerson Algorithm for Maximum Flow
1 parent abddc46 commit 97ea982

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/* Amit Bansal - @amitbansal7 */
2+
//References GeeksForGeeks
3+
#include <bits/stdc++.h>
4+
#include <string>
5+
#define lli long long int
6+
#define llu unsigned long long int
7+
#define S(x) scanf("%d",&x)
8+
#define Sl(x) scanf("%lld",&x)
9+
#define Mset(p,i) memset(p,i,sizeof(p))
10+
#define mlc(t,n) (t *)malloc(sizeof(t)*n)
11+
#define NIL -1
12+
#define INF INT_MAX
13+
#define TC int testcase; S(testcase); while(testcase--)
14+
#define Pi 3.14159
15+
using namespace std;
16+
17+
const int V = 6;
18+
19+
bool BFS(int graph[V][V],int s,int t,int parent[])
20+
{
21+
queue <int>Q;
22+
int visited[V];
23+
Mset(visited,0);
24+
visited[s] = 1;
25+
Q.push(s);
26+
parent[s] = NIL;
27+
28+
while(!Q.empty())
29+
{
30+
int u = Q.front();
31+
Q.pop();
32+
33+
for(int v=0;v<V;v++)
34+
{
35+
if(!visited[v] && graph[u][v] > 0)
36+
{
37+
Q.push(v);
38+
parent[v] = u;
39+
visited[v] = 1;
40+
}
41+
}
42+
}
43+
return(visited[t]);
44+
}
45+
46+
int FordFulkerson(int graph[V][V],int s,int t)
47+
{
48+
//residual graph
49+
int rGraph[V][V];
50+
memcpy(rGraph,graph,sizeof(int)*V*V);
51+
52+
int maxflow = 0;
53+
int parent[V];
54+
55+
while(BFS(rGraph,s,t,parent))
56+
{
57+
int u,v;
58+
int path_flow = INT_MAX;
59+
//finding minimum residual capacity along the augmented path.
60+
for(int v = t;v!=s;v = parent[v])
61+
{
62+
u = parent[v];
63+
path_flow = min(path_flow,rGraph[u][v]);
64+
}
65+
66+
for(v = t;v!=s;v=parent[v])
67+
{
68+
u = parent[v];
69+
rGraph[u][v] -= path_flow;
70+
rGraph[v][u] += path_flow;
71+
}
72+
73+
maxflow += path_flow;
74+
}
75+
76+
return maxflow;
77+
}
78+
79+
int main()
80+
{
81+
//CLRS fig 26.1(a)
82+
int graph[V][V] = {{0,16,12,0,0,0},
83+
{0,0,0,12,0,0},
84+
{0,4,0,0,14,0},
85+
{0,0,9,0,0,20},
86+
{0,0,0,7,0,4},
87+
{0,0,0,0,0,0}};
88+
89+
printf("Max flow is %d\n",FordFulkerson(graph,0,5));
90+
91+
return 0;
92+
}

0 commit comments

Comments
 (0)