美文网首页算法学习
算法题--二维地图唯一路径数

算法题--二维地图唯一路径数

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

0. 链接

题目链接

1. 题目

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

示意图

Above is a 7 x 3 grid. How many possible unique paths are there?

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

Constraints:

1 <= m, n <= 100
It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

2. 思路1:动态规划

image.png

对于(i, j)点, 由于robot只能向右或者向下, 所以它只可能由(i - 1, j)或(i, j - 1)格子通过向右或向下一次到达, 得到结论

若dp[i][j]表示到达(i,j)的唯一路径数, 则有

dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

初始条件为:

dp[i][0] = dp[0][j] = 1

原因是因为终点和起点在同一条直线上, 由于robot没法在向下后再向上到达终点, 所以它也只能通过走直线的方式抵达上述终点,即对于这些终点而言,只有1条路径。

3. 代码

# coding:utf8


class Solution:
    def uniquePaths(self, m: int, n: int) -> int:
        dp = [[0] * n for _ in range(m)]
        for i in range(m):
            dp[i][0] = 1
        for j in range(n):
            dp[0][j] = 1
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

        return dp[m - 1][n - 1]


def find_and_print(solution, m, n):
    print('m={}, n={}, output={}'.format(m, n, solution.uniquePaths(m, n)))


solution = Solution()
find_and_print(solution, 3, 2)
find_and_print(solution, 7, 3)

输出结果

m=3, n=2, output=3
m=7, n=3, output=28

4. 结果

image.png

相关文章

网友评论

    本文标题:算法题--二维地图唯一路径数

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