{"id":26369,"date":"2017-10-26T21:53:55","date_gmt":"2017-10-26T16:23:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26369"},"modified":"2017-10-26T21:53:55","modified_gmt":"2017-10-26T16:23:55","slug":"c-algorithm-ford-fulkerson-algorithm-maximum-flow-problem","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-algorithm-ford-fulkerson-algorithm-maximum-flow-problem\/","title":{"rendered":"Cpp Algorithm &#8211; Ford-Fulkerson Algorithm for Maximum Flow Problem"},"content":{"rendered":"<p>Given a graph which represents a flow network where every edge has a capacity. Also given two vertices <em>source <\/em>\u2018s\u2019 and <em>sink<\/em> \u2018t\u2019 in the graph, find the maximum possible flow from s to t with following constraints:<span id=\"more-119346\"><\/span><\/p>\n<p><strong>a)<\/strong> Flow on an edge doesn\u2019t exceed the given capacity of the edge.<\/p>\n<p><strong>b)<\/strong> Incoming flow is equal to outgoing flow for every vertex except s and t.<\/p>\n<p>For example, consider the following graph from CLRS book.<\/p>\n<p>The maximum possible flow in the above graph is 23.<\/p>\n<p>Prerequisite : <strong>Max Flow Problem Introduction<\/strong><\/p>\n<pre><strong>Ford-Fulkerson Algorithm<\/strong> \r\nThe following is simple idea of Ford-Fulkerson algorithm:\r\n<strong>1)<\/strong> Start with initial flow as 0.\r\n<strong>2) <\/strong>While there is a augmenting path from source to sink. \r\n           Add this path-flow to flow.\r\n<strong>3) <\/strong>Return flow.<\/pre>\n<p><strong>Time Complexity:<\/strong> Time complexity of the above algorithm is O(max_flow * E). We run a loop while there is an augmenting path. In worst case, we may add 1 unit flow in every iteration. Therefore the time complexity becomes O(max_flow * E).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>How to implement the above simple algorithm? <\/strong><br \/>\nLet us first define the concept of Residual Graph which is needed for understanding the implementation.<br \/>\n<em><strong>Residual Graph<\/strong><\/em> of a flow network is a graph which indicates additional possible flow. If there is a path from source to sink in residual graph, then it is possible to add flow. Every edge of a residual graph has a value called <strong><em>residual capacity<\/em><\/strong> which is equal to original capacity of the edge minus current flow. Residual capacity is basically the current capacity of the edge.<br \/>\nLet us now talk about implementation details. Residual capacity is 0 if there is no edge between two vertices of residual graph. We can initialize the residual graph as original graph as there is no initial flow and initially residual capacity is equal to original capacity. To find an augmenting path, we can either do a BFS or DFS of the residual graph. We have used BFS in below implementation. Using BFS, we can find out if there is a path from source to sink. BFS also builds parent[] array. Using the parent[] array, we traverse through the found path and find possible flow through this path by finding minimum residual capacity along the path. We later add the found path flow to overall flow.<br \/>\nThe important thing is, we need to update residual capacities in the residual graph. We subtract path flow from all edges along the path and we add path flow along the reverse edges We need to add path flow along reverse edges because may later need to send flow in reverse direction (See following link for example).<\/p>\n<p>Following are C++ and Java implementations of Ford-Fulkerson algorithm. To keep things simple, graph is represented as a 2D matrix.<\/p>\n<p><strong>C++ Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program for implementation of Ford Fulkerson algorithm<br\/>#include &lt;iostream&gt;<br\/>#include &lt;limits.h&gt;<br\/>#include &lt;string.h&gt;<br\/>#include &lt;queue&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Number of vertices in given graph<br\/>#define V 6<br\/> <br\/>\/* Returns true if there is a path from source &#039;s&#039; to sink &#039;t&#039; in<br\/>  residual graph. Also fills parent[] to store the path *\/<br\/>bool bfs(int rGraph[V][V], int s, int t, int parent[])<br\/>{<br\/>    \/\/ Create a visited array and mark all vertices as not visited<br\/>    bool visited[V];<br\/>    memset(visited, 0, sizeof(visited));<br\/> <br\/>    \/\/ Create a queue, enqueue source vertex and mark source vertex<br\/>    \/\/ as visited<br\/>    queue &lt;int&gt; q;<br\/>    q.push(s);<br\/>    visited[s] = true;<br\/>    parent[s] = -1;<br\/> <br\/>    \/\/ Standard BFS Loop<br\/>    while (!q.empty())<br\/>    {<br\/>        int u = q.front();<br\/>        q.pop();<br\/> <br\/>        for (int v=0; v&lt;V; v++)<br\/>        {<br\/>            if (visited[v]==false &amp;&amp; rGraph[u][v] &gt; 0)<br\/>            {<br\/>                q.push(v);<br\/>                parent[v] = u;<br\/>                visited[v] = true;<br\/>            }<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ If we reached sink in BFS starting from source, then return<br\/>    \/\/ true, else false<br\/>    return (visited[t] == true);<br\/>}<br\/> <br\/>\/\/ Returns the maximum flow from s to t in the given graph<br\/>int fordFulkerson(int graph[V][V], int s, int t)<br\/>{<br\/>    int u, v;<br\/> <br\/>    \/\/ Create a residual graph and fill the residual graph with<br\/>    \/\/ given capacities in the original graph as residual capacities<br\/>    \/\/ in residual graph<br\/>    int rGraph[V][V]; \/\/ Residual graph where rGraph[i][j] indicates <br\/>                     \/\/ residual capacity of edge from i to j (if there<br\/>                     \/\/ is an edge. If rGraph[i][j] is 0, then there is not)  <br\/>    for (u = 0; u &lt; V; u++)<br\/>        for (v = 0; v &lt; V; v++)<br\/>             rGraph[u][v] = graph[u][v];<br\/> <br\/>    int parent[V];  \/\/ This array is filled by BFS and to store path<br\/> <br\/>    int max_flow = 0;  \/\/ There is no flow initially<br\/> <br\/>    \/\/ Augment the flow while tere is path from source to sink<br\/>    while (bfs(rGraph, s, t, parent))<br\/>    {<br\/>        \/\/ Find minimum residual capacity of the edges along the<br\/>        \/\/ path filled by BFS. Or we can say find the maximum flow<br\/>        \/\/ through the path found.<br\/>        int path_flow = INT_MAX;<br\/>        for (v=t; v!=s; v=parent[v])<br\/>        {<br\/>            u = parent[v];<br\/>            path_flow = min(path_flow, rGraph[u][v]);<br\/>        }<br\/> <br\/>        \/\/ update residual capacities of the edges and reverse edges<br\/>        \/\/ along the path<br\/>        for (v=t; v != s; v=parent[v])<br\/>        {<br\/>            u = parent[v];<br\/>            rGraph[u][v] -= path_flow;<br\/>            rGraph[v][u] += path_flow;<br\/>        }<br\/> <br\/>        \/\/ Add path flow to overall flow<br\/>        max_flow += path_flow;<br\/>    }<br\/> <br\/>    \/\/ Return the overall flow<br\/>    return max_flow;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/\/ Let us create a graph shown in the above example<br\/>    int graph[V][V] = { {0, 16, 13, 0, 0, 0},<br\/>                        {0, 0, 10, 12, 0, 0},<br\/>                        {0, 4, 0, 0, 14, 0},<br\/>                        {0, 0, 9, 0, 0, 20},<br\/>                        {0, 0, 0, 7, 0, 4},<br\/>                        {0, 0, 0, 0, 0, 0}<br\/>                      };<br\/> <br\/>    cout &lt;&lt; &quot;The maximum possible flow is &quot; &lt;&lt; fordFulkerson(graph, 0, 5);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>The maximum possible flow is 23<\/pre>\n<p>The above implementation of Ford Fulkerson Algorithm is called <strong><a href=\"http:\/\/en.wikipedia.org\/wiki\/Edmonds%E2%80%93Karp_algorithm\" target=\"_blank\" rel=\"noopener noreferrer\">Edmonds-Karp Algorithm<\/a><\/strong>. The idea of Edmonds-Karp is to use BFS in Ford Fulkerson implementation as BFS always picks a path with minimum number of edges. When BFS is used, the worst case time complexity can be reduced to O(VE<sup>2<\/sup>). The above implementation uses adjacency matrix representation though where BFS takes O(V<sup>2<\/sup>) time, the time complexity of the above implementation is O(EV<sup>3<\/sup>) (Refer <a href=\"http:\/\/www.flipkart.com\/introduction-algorithms-3rd\/p\/itmczynzhyhxv2gs?pid=9788120340077&amp;affid=sandeepgfg\" target=\"_blank\" rel=\"noopener noreferrer\">CLRS book<\/a> for proof of time complexity)<\/p>\n<p>This is an important problem as it arises in many practical situations. Examples include, maximizing the transportation with given traffic limits, maximizing packet flow in computer networks.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C++ Algorithm &#8211; Ford-Fulkerson Algorithm for Maximum Flow Problem &#8211; Graph Algorithm &#8211; Given a graph which represents a flow network where every edge<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,83515,1,73906,78429],"tags":[78588,78589,78596,78595,78587,78594,78592,78590,78591,78593],"class_list":["post-26369","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-c-programming-3","category-coding","category-graph-algorithms","category-maximum-flow","tag-ford-fulkerson-algorithm-c-program","tag-ford-fulkerson-algorithm-example","tag-ford-fulkerson-algorithm-example-pdf","tag-ford-fulkerson-algorithm-geeksforgeeks","tag-ford-fulkerson-algorithm-pseudocode","tag-ford-fulkerson-algorithm-python","tag-ford-fulkerson-example-step-by-step","tag-ford-fulkerson-min-cut","tag-ford-fulkerson-runtime","tag-maximum-flow-problem-example"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26369","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26369"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26369\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26369"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26369"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26369"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}