[LeetCode]63 不同的路径总数之二

来源:互联网 发布:python怎么滤波图片 编辑:程序博客网 时间:2024/06/07 22:52

Unique Paths II(不同的路径总数之二)

【难度:Medium】
Follow up for “Unique Paths”:

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

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

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
这里写图片描述
LeetCode 62题的扩展,为机器人增加了障碍物,0表示空地,1表示障碍,同样求从左上角到右下角不同的走法总数。


解题思路

在62题的基础上解决这个问题,但需要考虑的是,机器人不能简单地向下或向右走,要判断是否有障碍物,因此左边界和上边界的初始化也要根据上一个点的状态来设置,同样使用动态规划来完成。


c++代码如下:

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {        if (obstacleGrid.empty())            return 0;        //入口有障碍的话,直接返回        if (obstacleGrid[0][0] == 1)            return 0;        int m = obstacleGrid.size();        int n = obstacleGrid[0].size();        vector<vector<int>> path(m,vector<int>(n,0));        //入口点走法只有1种。        path[0][0] = 1;        for (int i = 1; i < m; i++) {            //左边界,如果上一点可行并且当前点没有障碍物,那么该点可走            if (path[i-1][0] != 0 && obstacleGrid[i][0] != 1)                path[i][0] = 1;        }        for (int i = 1; i < n; i++) {            //上边界与左边界情况同理            if (path[0][i-1] != 0 && obstacleGrid[0][i] != 1)                path[0][i] = 1;        }        for (int i = 1; i < m; i++)            for (int j = 1; j < n; j++)                //动态规划,当前点无障碍物则与62题处理方法一致                if (obstacleGrid[i][j] != 1)                    path[i][j] = path[i-1][j]+path[i][j-1];        return path[m-1][n-1];    }};
0 0
原创粉丝点击