算法学习

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

2020-04-16  本文已影响0人  岁月如歌2020
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]
dp[i][0] = dp[i - 1][0] + grid[i][0]
dp[0][j] = dp[0][j - 1] + grid[0][j]
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
上一篇下一篇

猜你喜欢

热点阅读