Minimum Path Sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have a m x n matrix filled with non-negative integers, find a path from top left corner to bottom right corner which minimizes the sum of all numbers along its path. Movements can only be either down or right at any point in time. So for example, if the matrix is like below

131
151
421

The output will be 7, the path will be 1,3,1,1,1, this will minimize the sum

Let us see the steps −

  • a := number of rows, b := number of columns
  • i := a – 1, j := b – 1
  • while j >= 0
    • matrix[a, j] := matrix[a, j] + matrix[a, j + 1]
    • decrease j by 1
  • while i >= 0
    • matrix[i, b] := matrix[i, b] + matrix[i + 1, b]
    • decrease i by 1
  • j := b – 1 and i := row – 1
  • while i >= 0
    • while j >= 0
      • matrix[i, j] := matrix[i, j] + minimum of matrix[i, j + 1] and matrix[i + 1, j]
      • decrease j by 1
    • j := b – 1
    • i := i – 1
  • return matrix[0, 0]

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def minPathSum(self, grid):
      row = len(grid)-1
      column = len(grid[0])-1
      i=row-1
      j=column-1
      while j>=0:
         grid[row][j]+=grid[row][j+1]
         j-=1
      while i>=0:
         grid[i][column]+=grid[i+1][column]
         i-=1
      j=column-1
     i = row-1
      while i>=0:
         while j>=0:
            grid[i][j] += min(grid[i][j+1],grid[i+1][j])
            j-=1
         j=column-1
         i-=1
      return(grid[0][0])
ob1 = Solution()
print(ob1.minPathSum([[1,3,1],[1,5,1],[4,2,1]]))

Input

[[1,3,1],[1,5,1],[4,2,1]]

Output

7
raja
Published on 28-Apr-2020 10:55:14
Advertisements