8.Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to 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.

Example:
Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1β†’3β†’1β†’1β†’1 minimizes the sum.

Solution : (Dynamic Programming)

Approach same as unique paths

class Solution
{
public:
    int minPathSum(vector<vector<int>> &grid)
    {

        int n = grid.size();
        int m = grid[0].size();

        int arr[n][m];
        arr[0][0] = grid[0][0];

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (i == 0 && j == 0)
                {
                    continue;
                }
                
                if (i == 0)
                {
                    arr[i][j] = arr[i][j - 1] + grid[i][j];
                }
                else if (j == 0)
                {
                    arr[i][j] = arr[i - 1][j] + grid[i][j];
                }
                else
                {
                    arr[i][j] = grid[i][j] + min(arr[i - 1][j], arr[i][j - 1]);
                }
            }
        }
        

        return arr[n - 1][m - 1];
    }
};

Time Complexity: O(NM) , Space Complexity: O(NM)

Last updated