首页 > 代码库 > LeetCode 64. Minimum Path Sum 20170515

LeetCode 64. Minimum Path Sum 20170515

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.

题目大意:给定一个一个m*n格的方针,每个方格都放一个非负数,找到一条从左上角到右下角的路使得经过的格子的数字之和最小。只能往右走或者往下走

解题思路:

构建一个大小为m*n的矩阵,矩阵内每个值为从起点走到该点的最短距离,直到终点。

分为三种情况

1、第一列每个格只能从它的上一个格走下来,所以最左边一列的数为它上面一个点的值加上原方阵中该点位置上的值

2、第一行每个格只能从它的左边一个格走过来,所以最上边一行的数为它左边一个点的值加上原方阵中该点位置上的值

3、如果不是在第一行或者第一列,则该方格可以从它上面一个格走下来或者从它左边一个格做过来,因此需要比较上面一格的数值和左边一格的数值

    求出最小值,再加上方阵中该格的数值。

技术分享

class Solution(object):
  def minPathSum(self, grid):
    """
    :type grid: List[List[int]]
    :rtype: int
    """

    m = len(grid)
    n = len(grid[0])
    grid1 = [[0 for i in range(n)] for j in range(m)]
    grid1[0][0] = grid[0][0]
    for i in range(0, m):
      for j in range(0, n):
        if i != 0 and j == 0:
          grid1[i][j] = grid1[i - 1][j] + grid[i][j]
        elif i == 0 and j != 0:
          grid1[i][j] = grid1[i][j - 1] + grid[i][j]
        elif i != 0 and j != 0:
          grid1[i][j] = min(grid1[i - 1][j],grid1[i][j - 1]) + grid[i][j]
    return grid1[m - 1][n - 1]

 

LeetCode 64. Minimum Path Sum 20170515