{"id":25955,"date":"2017-10-25T22:06:41","date_gmt":"2017-10-25T16:36:41","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25955"},"modified":"2017-10-25T22:06:41","modified_gmt":"2017-10-25T16:36:41","slug":"c-programming-min-cost-path","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-min-cost-path\/","title":{"rendered":"Cpp Programming &#8211; Min Cost Path"},"content":{"rendered":"<p>Given a cost matrix cost[][] and a position (m, n) in cost[][], write a function that returns cost of minimum cost path to reach (m, n) from (0, 0). Each cell of the matrix represents a cost to traverse through that cell. <span id=\"more-14943\"><\/span>Total cost of a path to reach (m, n) is sum of all the costs on that path (including both source and destination). You can only traverse down, right and diagonally lower cells from a given cell, i.e., from a given cell (i, j), cells (i+1, j), (i, j+1) and (i+1, j+1) can be traversed. You may assume that all costs are positive integers.<\/p>\n<p>For example, in the following figure, what is the minimum cost path to (2, 2)?<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-25961\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Min-Cost.png\" alt=\"Min Cost Path\" width=\"279\" height=\"242\" \/><\/p>\n<p>The path with minimum cost is highlighted in the following figure. The path is (0, 0) \u2013&gt; (0, 1) \u2013&gt; (1, 2) \u2013&gt; (2, 2). The cost of the path is 8 (1 + 2 + 2 + 3).<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-25964\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Min-Cost-Path.png\" alt=\"Min Cost Path\" width=\"279\" height=\"242\" \/><\/p>\n<ul>\n<li><strong>Optimal Substructure<\/strong><br \/>\nThe path to reach (m, n) must be through one of the 3 cells: (m-1, n-1) or (m-1, n) or (m, n-1). So minimum cost to reach (m, n) can be written as \u201cminimum of the 3 cells plus cost[m][n]\u201d.<\/li>\n<\/ul>\n<p>minCost(m, n) = min (minCost(m-1, n-1), minCost(m-1, n), minCost(m, n-1)) + cost[m][n]\n<ul>\n<li><strong>Overlapping Subproblems<\/strong><br \/>\nFollowing is simple recursive implementation of the MCP (Minimum Cost Path) problem. The implementation simply follows the recursive structure mentioned above.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/* A Naive recursive implementation of MCP(Minimum Cost Path) problem *\/<br\/>#include&lt;stdio.h&gt;<br\/>#include&lt;limits.h&gt;<br\/>#define R 3<br\/>#define C 3<br\/> <br\/>int min(int x, int y, int z);<br\/> <br\/>\/* Returns cost of minimum cost path from (0,0) to (m, n) in mat[R][C]*\/<br\/>int minCost(int cost[R][C], int m, int n)<br\/>{<br\/>   if (n &lt; 0 || m &lt; 0)<br\/>      return INT_MAX;<br\/>   else if (m == 0 &amp;&amp; n == 0)<br\/>      return cost[m][n];<br\/>   else<br\/>      return cost[m][n] + min( minCost(cost, m-1, n-1),<br\/>                               minCost(cost, m-1, n), <br\/>                               minCost(cost, m, n-1) );<br\/>}<br\/> <br\/>\/* A utility function that returns minimum of 3 integers *\/<br\/>int min(int x, int y, int z)<br\/>{<br\/>   if (x &lt; y)<br\/>      return (x &lt; z)? x : z;<br\/>   else<br\/>      return (y &lt; z)? y : z;<br\/>}<br\/> <br\/>\/* Driver program to test above functions *\/<br\/>int main()<br\/>{<br\/>   int cost[R][C] = { {1, 2, 3},<br\/>                      {4, 8, 2},<br\/>                      {1, 5, 3} };<br\/>   printf(&quot; %d &quot;, minCost(cost, 2, 2));<br\/>   return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>It should be noted that the above function computes the same subproblems again and again. See the following recursion tree, there are many nodes which appear more than once. Time complexity of this naive recursive solution is exponential and it is terribly slow.<\/p>\n[ad type=&#8221;banner&#8221;]\n<pre>mC refers to minCost()\r\n                                    mC(2, 2)\r\n                          \/            |           \\\r\n                         \/             |            \\             \r\n                 mC(1, 1)           mC(1, 2)             mC(2, 1)\r\n              \/     |     \\       \/     |     \\           \/     |     \\ \r\n             \/      |      \\     \/      |      \\         \/      |       \\\r\n       mC(0,0) mC(0,1) mC(1,0) mC(0,1) mC(0,2) mC(1,1) mC(1,0) mC(1,1) mC(2,0) \r\n<\/pre>\n<p>So the MCP problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array tc[][] in bottom up manner.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C++<\/span> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/* Dynamic Programming implementation of MCP problem *\/<br\/>#include&lt;stdio.h&gt;<br\/>#include&lt;limits.h&gt;<br\/>#define R 3<br\/>#define C 3<br\/> <br\/>int min(int x, int y, int z);<br\/> <br\/>int minCost(int cost[R][C], int m, int n)<br\/>{<br\/>     int i, j;<br\/> <br\/>     \/\/ Instead of following line, we can use int tc[m+1][n+1] or <br\/>     \/\/ dynamically allocate memoery to save space. The following line is<br\/>     \/\/ used to keep te program simple and make it working on all compilers.<br\/>     int tc[R][C];  <br\/> <br\/>     tc[0][0] = cost[0][0];<br\/> <br\/>     \/* Initialize first column of total cost(tc) array *\/<br\/>     for (i = 1; i &lt;= m; i++)<br\/>        tc[i][0] = tc[i-1][0] + cost[i][0];<br\/> <br\/>     \/* Initialize first row of tc array *\/<br\/>     for (j = 1; j &lt;= n; j++)<br\/>        tc[0][j] = tc[0][j-1] + cost[0][j];<br\/> <br\/>     \/* Construct rest of the tc array *\/<br\/>     for (i = 1; i &lt;= m; i++)<br\/>        for (j = 1; j &lt;= n; j++)<br\/>            tc[i][j] = min(tc[i-1][j-1], <br\/>                           tc[i-1][j], <br\/>                           tc[i][j-1]) + cost[i][j];<br\/> <br\/>     return tc[m][n];<br\/>}<br\/> <br\/>\/* A utility function that returns minimum of 3 integers *\/<br\/>int min(int x, int y, int z)<br\/>{<br\/>   if (x &lt; y)<br\/>      return (x &lt; z)? x : z;<br\/>   else<br\/>      return (y &lt; z)? y : z;<br\/>}<br\/> <br\/>\/* Driver program to test above functions *\/<br\/>int main()<br\/>{<br\/>   int cost[R][C] = { {1, 2, 3},<br\/>                      {4, 8, 2},<br\/>                      {1, 5, 3} };<br\/>   printf(&quot; %d &quot;, minCost(cost, 2, 2));<br\/>   return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>8<\/pre>\n<p>Time Complexity of the DP implementation is O(mn) which is much better than Naive Recursive implementation.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C++ Programming &#8211; Min Cost Path &#8211; Dynamic Programming &#8211; the MCP problem has both properties of a dynamic programming problem. Like other typical DP problems,<\/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,70145],"tags":[72847,76402,72842,72845,70483,76394,72841,72848,72840,72849,72846,72843,72854,72844,72850,76404,76396,76398,72839,76405,76401,76400,76399,76409,76395,76407,76397,76408,72852,72855,72853,72851],"class_list":["post-25955","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-c-programming-3","category-coding","category-dynamic-programming","tag-concept-of-dynamic-programming","tag-count-all-possible-paths-from-top-left-to-bottom-right-of-a-mxn-matrix","tag-define-dynamic-programming","tag-definition-of-dynamic-programming","tag-dynamic-programming","tag-dynamic-programming-and-min-cost-path","tag-dynamic-programming-c","tag-dynamic-programming-code-generation-algorithm","tag-dynamic-programming-definition","tag-dynamic-programming-in-c","tag-dynamic-programming-in-data-structure","tag-dynamic-programming-problems","tag-dynamic-programming-set-1","tag-dynamic-programming-software","tag-explain-dynamic-programming","tag-find-all-paths-in-a-matrix","tag-find-minimum-cost-path","tag-finding-path-in-minimum-cost-path-algo-using-dynamic-programming","tag-how-to-solve-dynamic-programming-problems","tag-maximum-sum-in-path-through-a-2d-array","tag-maximum-sum-path-in-a-matrix","tag-min-cost-path","tag-minimum-cost-path-dp-example","tag-minimum-cost-path-c","tag-minimum-cost-path-dynamic-programming","tag-minimum-cost-path-in-c","tag-minimum-cost-path-problem","tag-minimum-cost-path-problem-c","tag-problems-on-dynamic-programming","tag-simple-dynamic-programming-example","tag-types-of-dynamic-programming","tag-youtube-dynamic-programming"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25955","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=25955"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25955\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25955"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25955"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25955"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}