
Sponsored
Sponsored
This approach involves modifying the input grid in place to store the minimum path sum to each cell. Since we can only move right or down, the minimum path sum to each cell is the value of that cell plus the minimum of the sum from the above or left cell. Start by updating the first row and column as they can only be reached by a single direction. Then, fill in the rest of the grid by selecting the minimum path from top or left for each cell.
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns, as each cell is visited once.
Space Complexity: O(1) as we modify the grid in place.
1class Solution:
2 def minPathSum(self, grid: List[List[int]]) -> int:
3 m, n = len(grid), len(grid[0])
4 for i in range(1, m):
5 grid[i][0] += grid[i - 1][0]
6 for j in range(1, n):
7 grid[0][j] += grid[0][j - 1]
8
9 for i in range(1, m):
10 for j in range(1, n):
11 grid[i][j] += min(grid[i-1][j], grid[i][j-1])
12
13 return grid[m-1][n-1]The Python code solves the problem by updating the grid in place to reflect the minimum path sum to each cell. It uses list slicing and loops to compute the results.
Rather than modifying the input grid, this approach uses an additional 2D array to store the minimum path sums. Start by initializing the first cell to the first cell of the grid. For the first row and first column, accumulate sums as they can only come from one direction. For the rest of the cells, compute the minimum path by taking the minimum of the paths leading from the top or left cell, and store the result in the auxiliary DP array.
Time Complexity: O(m * n).
Space Complexity: O(m * n) due to the additional 2D array used.
1 public int MinPathSum(int[][] grid) {
int m = grid.Length;
int n = grid[0].Length;
int[][] dp = new int[m][];
for (int i = 0; i < m; i++) {
dp[i] = new int[n];
}
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] = grid[i][j] + Math.Min(dp[i-1][j], dp[i][j-1]);
}
}
return dp[m-1][n-1];
}
}The C# implementation utilizes an auxiliary DP array to compute minimum path sums efficiently and ensure the original grid remains unaltered.