Given a m x n
grid filled with non-negative numbers, find a path from the top left to the bottom right, which minimizes the sum of all numbers along its path. You can only move either down or right at any point in time.
This problem can be efficiently solved using Dynamic Programming (DP). Here’s the strategy:
dp
where dp[i][j]
will store the minimum path sum to reach the cell (i, j)
.dp[0][0]
will just be grid[0][0]
as it is the starting point.dp[0][j]
can only be reached from the left, so we sum up values from the leftmost column.dp[i][0]
can only be reached from the top, so we sum up values from the topmost row.(i, j)
, the minimum path sum can be found by taking the minimum of the paths coming from the top (dp[i-1][j]
) or from the left (dp[i][j-1]
).dp[m-1][n-1]
will be the minimum path sum to reach the bottom-right corner.Here’s the implementation of the above strategy:
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = grid[0][0];
// Initialize the first row
for (int j = 1; j < n; ++j) {
dp[0][j] = dp[0][j-1] + grid[0][j];
}
// Initialize the first column
for (int i = 1; i < m; ++i) {
dp[i][0] = dp[i-1][0] + grid[i][0];
}
// Fill the rest of the dp table
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];
}
};
m
is the number of rows and n
is the number of columns. We are iterating through each cell in the grid once.This approach ensures optimal performance while respecting constraints typical of competitive programming problems.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?