1
+ // C++ program for implementation of Ford Fulkerson algorithm
2
+ #include < iostream>
3
+ #include < limits.h>
4
+ #include < string.h>
5
+ #include < queue>
6
+ using namespace std ;
7
+
8
+ #define V 6
9
+
10
+ bool bfs (int rGraph[V][V], int s, int t, int parent[])
11
+ {
12
+ // Create a visited array and mark all vertices as not visited
13
+ bool visited[V];
14
+ memset (visited, 0 , sizeof (visited));
15
+
16
+ // Create a queue, enqueue source vertex and mark source vertex
17
+ // as visited
18
+ queue <int > q;
19
+ q.push (s);
20
+ visited[s] = true ;
21
+ parent[s] = -1 ;
22
+
23
+ // Standard BFS Loop
24
+ while (!q.empty ())
25
+ {
26
+ int u = q.front ();
27
+ q.pop ();
28
+
29
+ for (int v=0 ; v<V; v++)
30
+ {
31
+ if (visited[v]==false && rGraph[u][v] > 0 )
32
+ {
33
+ q.push (v);
34
+ parent[v] = u;
35
+ visited[v] = true ;
36
+ }
37
+ }
38
+ }
39
+
40
+ return (visited[t] == true );
41
+ }
42
+
43
+ int fordFulkerson (int graph[V][V], int s, int t)
44
+ {
45
+ int u, v;
46
+
47
+
48
+ int rGraph[V][V];
49
+ for (u = 0 ; u < V; u++)
50
+ for (v = 0 ; v < V; v++)
51
+ rGraph[u][v] = graph[u][v];
52
+
53
+ int parent[V];
54
+
55
+ int max_flow = 0 ;
56
+
57
+ // Augment the flow while tere is path from source to sink
58
+ while (bfs (rGraph, s, t, parent))
59
+ {
60
+
61
+ int path_flow = INT_MAX;
62
+ for (v=t; v!=s; v=parent[v])
63
+ {
64
+ u = parent[v];
65
+ path_flow = min (path_flow, rGraph[u][v]);
66
+ }
67
+
68
+ for (v=t; v != s; v=parent[v])
69
+ {
70
+ u = parent[v];
71
+ rGraph[u][v] -= path_flow;
72
+ rGraph[v][u] += path_flow;
73
+ }
74
+
75
+ max_flow += path_flow;
76
+ }
77
+
78
+ return max_flow;
79
+ }
80
+
81
+ int main ()
82
+ {
83
+ // Let us create a graph shown in the above example
84
+ int graph[V][V] = { {0 , 16 , 13 , 0 , 0 , 0 },
85
+ {0 , 0 , 10 , 12 , 0 , 0 },
86
+ {0 , 4 , 0 , 0 , 14 , 0 },
87
+ {0 , 0 , 9 , 0 , 0 , 20 },
88
+ {0 , 0 , 0 , 7 , 0 , 4 },
89
+ {0 , 0 , 0 , 0 , 0 , 0 }
90
+ };
91
+
92
+ cout << " The maximum possible flow is " << fordFulkerson (graph, 0 , 5 );
93
+
94
+ return 0 ;
95
+ }
0 commit comments