您的位置:首页 > 其它

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

2016-02-28 13:42 465 查看

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];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: