Minimum Path Sum Algorithm
The Minimum Path Sum Algorithm is an optimization technique used in dynamic programming and graph theory, which aims to find the minimum sum of the values of the elements along a path in a grid, from the top-left corner to the bottom-right corner, moving only right or down. In a given grid or matrix, each cell contains a non-negative integer value representing the cost of traversing that cell. The algorithm computes the most cost-efficient path, i.e., the path with the minimum total cost, while adhering to the specified movement constraints.
The algorithm is typically implemented using dynamic programming, which uses a bottom-up approach to calculate the minimum path sum by filling up a memoization table. The memoization table, usually of the same size as the input grid, stores the minimum sum to reach each cell from the top-left corner. The algorithm starts by initializing the first row and column of the memoization table with the cumulative sums of the corresponding cells in the input grid. Then, it iteratively fills up the remaining cells in the memoization table by choosing the minimum of the two neighboring cells (either the cell above or the cell to the left) and adding the current cell's value from the input grid. Finally, the minimum path sum is obtained from the bottom-right corner of the memoization table. This algorithm has a time complexity of O(m*n), where m and n are the dimensions of the input grid.
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int m = grid.size();
if (m == 0) return 0;
int n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = grid[0][0];
for (int i = 1; i < m; i++)
dp[i][0] = dp[i-1][0] + grid[i][0];
for (int j = 1; j < n; j++)
dp[0][j] = dp[0][j-1] + grid[0][j];
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++)
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
return dp[m-1][n-1];
}
};
// O(n) space
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if (grid.empty()) {
return 0;
}
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(2, vector<int>(n, 0));
int T1 = 1;
int T2 = 0;
for (int i = 0; i < m; i++) {
T1 ^= 1;
T2 ^= 1;
dp[T2][0] = dp[T1][0] + grid[i][0];
for (int j = 1; j < n; j++) {
if (i == 0) {
dp[T2][j] = dp[T2][j-1] + grid[i][j];
} else {
dp[T2][j] = grid[i][j] + min(dp[T1][j], dp[T2][j-1]);
}
}
}
return dp[T2][n-1];
}
};