DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

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.

Note: You can only move either down or right at any point in time.

Example 1:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:

Input: grid = [[1,2,3],[4,5,6]]
Output: 12

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 100

SOLUTION:

class Solution:
    def calcMin(self, grid, x, y, m, n):
        if (x, y) in self.cache:
            return self.cache[(x, y)]
        if (x, y) == (m - 1, n - 1):
            self.cache[(x, y)] = grid[m - 1][n - 1]
            return self.cache[(x, y)]
        right = float('inf')
        bottom = float('inf')
        if y < n - 1:
            right = self.calcMin(grid, x, y + 1, m, n)
        if x < m - 1:
            bottom = self.calcMin(grid, x + 1, y, m, n)
        currMin = min(right, bottom)
        self.cache[(x, y)] = grid[x][y] + currMin
        return self.cache[(x, y)]

    def minPathSum(self, grid: List[List[int]]) -> int:
        self.cache = {}
        return self.calcMin(grid, 0, 0, len(grid), len(grid[0]))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)