美文网首页算法学习
算法题--二维地图最短路径长度

算法题--二维地图最短路径长度

作者: 岁月如歌2020 | 来源:发表于2020-04-16 22:29 被阅读0次
    image.png

    0. 链接

    题目链接

    1. 题目

    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:

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

    2. 思路1:动态规划

    image.png

    dp[i][j]表示到达(i,j)的最短路径长度, 则

    • 初始条件为:
    dp[0][0] = grid[0][0]
    
    • 对于i > 0, j = 0
      因为(i, 0)只能由(i - 1, 0)向下一步到达, 所以
    dp[i][0] = dp[i - 1][0] + grid[i][0]
    
    • 对于i = 0, j > 0
      因为(0, j)只能由(0, j - 1)向右一步到达, 所以
    dp[0][j] = dp[0][j - 1] + grid[0][j]
    
    • 对于i > 0 and j > 0
      因为(i, j)只能由(i - 1, j)向下一步或(i, j - 1)向右一步到达,所以
    dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
    

    3. 代码

    # coding:utf8
    from typing import List
    
    
    class Solution:
        def minPathSum(self, grid: List[List[int]]) -> int:
            m = len(grid)
            n = len(grid[0])
    
            dp = [[0] * n for _ in range(m)]
            dp[0][0] = grid[0][0]
    
            for i in range(1, m):
                dp[i][0] = dp[i - 1][0] + grid[i][0]
    
            for j in range(1, n):
                dp[0][j] = dp[0][j - 1] + grid[0][j]
    
            for i in range(1, m):
                for j in range(1, n):
                    dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
    
            return dp[m - 1][n - 1]
    
    
    solution = Solution()
    grid = [
      [1,3,1],
      [1,5,1],
      [4,2,1]
    ]
    print('input={}, output={}'.format(grid, solution.minPathSum(grid)))
    
    

    输出结果

    input=[[1, 3, 1], [1, 5, 1], [4, 2, 1]], output=7
    

    4. 结果

    image.png

    相关文章

      网友评论

        本文标题:算法题--二维地图最短路径长度

        本文链接:https://www.haomeiwen.com/subject/djmjvhtx.html