Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program for Minimum Cost Path
The minimum cost path problem involves finding the path from the top-left corner to the bottom-right corner of a 2D matrix with minimum total cost. You can only move right or down from any given cell. Dynamic programming provides an efficient solution to this problem.
Syntax
int minCostPath(int cost[][COLS], int m, int n);
Problem Approach
The solution uses dynamic programming to build a table where each cell contains the minimum cost to reach that position from the starting point (0,0). The formula for any cell (i,j) is −
dp[i][j] = cost[i][j] + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
Example: Dynamic Programming Solution
This example demonstrates finding the minimum cost path using dynamic programming −
#include <stdio.h>
#define R 3
#define C 3
int min(int a, int b, int c) {
if (a < b)
return (a < c) ? a : c;
else
return (b < c) ? b : c;
}
int minCostPath(int cost[R][C], int m, int n) {
int i, j;
int dp[R][C];
dp[0][0] = cost[0][0];
/* Fill first row */
for (j = 1; j <= n; j++)
dp[0][j] = dp[0][j-1] + cost[0][j];
/* Fill first column */
for (i = 1; i <= m; i++)
dp[i][0] = dp[i-1][0] + cost[i][0];
/* Fill remaining cells */
for (i = 1; i <= m; i++) {
for (j = 1; j <= n; j++) {
dp[i][j] = cost[i][j] + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]);
}
}
return dp[m][n];
}
int main() {
int cost[R][C] = {
{1, 2, 3},
{4, 8, 2},
{1, 5, 3}
};
printf("Minimum cost path: %d
", minCostPath(cost, 2, 2));
return 0;
}
Minimum cost path: 8
Key Points
- Time Complexity: O(m × n) where m and n are matrix dimensions
- Space Complexity: O(m × n) for the DP table
- Can be optimized to O(min(m,n)) space by using only one row/column
- Only three possible moves: diagonal, up, and left (relative to current position)
Conclusion
The minimum cost path problem is efficiently solved using dynamic programming with O(mn) time complexity. This approach avoids redundant calculations by storing intermediate results in a DP table.
