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.

 Notice

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

Solution

class Solution:
    """
    @param grid: a list of lists of integers.
    @return: An integer, minimizes the sum of all numbers along its path
    """
    def minPathSum(self, grid):
        # write your code here
        if grid == None or len(grid) == 0:
            return -1
        m = len(grid)
        n = len(grid[0])

        F = [[0 for y in range(n)] for x in range(m)]

        F[0][0] = grid[0][0]

        for i in range(1, m):
            F[i][0] = F[i-1][0] + grid[i][0]
        for j in range(1, n):
            F[0][j] = F[0][j-1] + grid[0][j]

        for i in range(1, m):
            for j in range(1, n):
                F[i][j] = min(F[i][j-1], F[i-1][j]) + grid[i][j]

        return F[-1][-1]

Last updated

Was this helpful?