Friday, November 24, 2017

Part-4,Min Cost Path

From (0,0)  to  (R,R)



                                                      Use Of Dynamic Programming 
                                                      TIME  COMPLEXITY  O(m*n)  


#include<bits/stdc++.h>

using namespace std;

int minCost(int cost[R][C], int m, int n)
{
     int i, j;
     int dp[R][C]; 

     dp[0][0] = cost[0][0];

     /* Initialize first column of total cost(tc) array */
     for (i = 1; i <= m; i++)
        dp[i][0] = dp[i-1][0] + cost[i][0];

     /* Initialize first row of tc array */
     for (j = 1; j <= n; j++)
        dp[0][j] = dp[0][j-1] + cost[0][j];

     /* Construct rest of the tc array */
     for (i = 1; i <= m; i++)
        for (j = 1; j <= n; j++)
            dp[i][j] = min(dp[i-1][j-1],
                           dp[i-1][j],
                           dp[i][j-1]) + cost[i][j];

     return dp[m][n];
}

int main()
{
   int cost[R][C] = { {1, 2, 3},
                      {4, 8, 2},
                      {1, 5, 3} };
   printf(" %d ", minCost(cost, 2, 2));
   return 0;
}



No comments:

Post a Comment