最小路径和

LintCode题目地址

给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。

#f数组:存储走到当前点的和最小值
# m,n是grid行数,列数
def minPathSum(self, grid):
        # write your code here
        
        m = len(grid)
        n = len(grid[0])
        f = [[0 for col in range(n)] for row in range(m)]
        for i in range(m):
            for j in range(n):
                if i == 0 and j == 0:
                    f[i][j] = grid[i][j]
                elif i == 0 or j == 0:
                    if i == 0:
                        f[0][j] = grid[0][j]+f[0][j-1]
                    else:
                        f[i][0] = grid[i][0]+f[i-1][0]
                else:
                    f[i][j] = min(f[i-1][j], f[i][j-1])+grid[i][j]
        return f[m-1][n-1]

你可能感兴趣的:(最小路径和)