
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.
1#include <stdio.h>
2
3int minPathSum(int** grid, int gridSize, int* gridColSize) {
4 for(int i = 1; i < gridSize; ++i) {
5 grid[i][0] += grid[i-1][0];
6 }
7 for(int j = 1; j < gridColSize[0]; ++j) {
8 grid[0][j] += grid[0][j-1];
9 }
10
11 for(int i = 1; i < gridSize; ++i) {
12 for(int j = 1; j < gridColSize[i]; ++j) {
13 grid[i][j] += (grid[i-1][j] < grid[i][j-1] ? grid[i-1][j] : grid[i][j-1]);
14 }
15 }
16
17 return grid[gridSize-1][gridColSize[gridSize-1]-1];
18}This C code uses nested loops to update the grid in place. The first loop updates the first column, and the second loop updates the first row. Then the nested loops calculate the minimum path sum for the rest of the grid by considering the minimum of the top and left cells. The function returns the bottom-right corner of the grid, which now contains the minimum path sum.
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
This C solution uses a separate 2D array to store the computed minimum path sums. Memory is dynamically allocated for storing sums; after computing the path, memory is freed.