欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现LeetCode(63.不同的路径之二)

程序员文章站 2022-06-24 11:28:11
[leetcode] 63. unique paths ii 不同的路径之二a robot is located at the top-left corner of a m x...

[leetcode] 63. unique paths ii 不同的路径之二

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).

now consider if some obstacles are added to the grids. how many unique paths would there be?

C++实现LeetCode(63.不同的路径之二)

an obstacle and empty space is marked as 1 and 0 respectively in the grid.

note: m and n will be at most 100.

example 1:

input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
output: 2
explanation:
there is one obstacle in the middle of the 3x3 grid above.
there are two ways to reach the bottom-right corner:
1. right -> right -> down -> down
2. down -> down -> right -> right

这道题是之前那道 unique paths 的延伸,在路径中加了一些障碍物,还是用动态规划 dynamic programming 来解,使用一个二维的 dp 数组,大小为 (m+1) x (n+1),这里的 dp[i][j] 表示到达 (i-1, j-1) 位置的不同路径的数量,那么i和j需要更新的范围就是 [1, m] 和 [1, n]。状态转移方程跟之前那道题是一样的,因为每个位置只能由其上面和左面的位置移动而来,所以也是由其上面和左边的 dp 值相加来更新当前的 dp 值,如下所示:

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

这里就能看出来初始化 d p数组的大小为 (m+1) x (n+1),是为了 handle 边缘情况,当i或j为0时,减1可能会出错。当某个位置是障碍物时,其 dp 值为0,直接跳过该位置即可。这里还需要初始化 dp 数组的某个值,使得其能正常累加。当起点不是障碍物时,其 dp 值应该为1,即dp[1][1] = 1,由于其是由 dp[0][1] + dp[1][0] 更新而来,所以二者中任意一个初始化为1即可。由于之后 leetcode 更新了这道题的 test case,使得使用 int 型的 dp 数组会有溢出的错误,所以改为使用 long 型的数组来避免 overflow,代码如下:

解法一:

class solution {
public:
    int uniquepathswithobstacles(vector<vector<int>>& obstaclegrid) {
        if (obstaclegrid.empty() || obstaclegrid[0].empty() || obstaclegrid[0][0] == 1) return 0;
        int m = obstaclegrid.size(), n = obstaclegrid[0].size();
        vector<vector<long>> dp(m + 1, vector<long>(n + 1, 0));
        dp[0][1] = 1;
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (obstaclegrid[i - 1][j - 1] != 0) continue;
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m][n];
    }
};

或者我们也可以使用一维 dp 数组来解,省一些空间,参见代码如下:

解法二:

class solution {
public:
    int uniquepathswithobstacles(vector<vector<int>>& obstaclegrid) {
        if (obstaclegrid.empty() || obstaclegrid[0].empty() || obstaclegrid[0][0] == 1) return 0;
        int m = obstaclegrid.size(), n = obstaclegrid[0].size();
        vector<long> dp(n, 0);
        dp[0] = 1;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (obstaclegrid[i][j] == 1) dp[j] = 0;
                else if (j > 0) dp[j] += dp[j - 1];
            }
        }
        return dp[n - 1];
    }
};

到此这篇关于c++实现leetcode(63.不同的路径之二)的文章就介绍到这了,更多相关c++实现不同的路径之二内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!