算法练习(15) —— Unique Paths II

算法练习(15) —— Unique Paths II

习题

本题取自 leetcode 中的 Dynamic Programming 栏目中的第63题:
Unique Paths II


题目如下:

Description

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.

Example

There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
[0,0,0],
[0,1,0],
[0,0,0]
]

The total number of unique paths is 2.

Note

m and n will be at most 100.

思路与代码

  • 这题衔接着上一题 Unique Paths ,具体可看算法练习(14)
  • II 与 I 主要的不同是其中添加了障碍物。添加了障碍物之后,就没办法这么简单的计算了。毕竟如果原本没有障碍物,长为m,宽为n,甚至可以简单地用排列组合算出:C(n-1)[(m-1)*(n-1)]
  • 增加了障碍物之后,就必须考虑几种情况:
    • 自身所在地点为障碍物 : 将本地点设为0,因为不能通过,所以独立的通路数肯定也为0。这个无论障碍是在边界还是非边界都适用
    • 自身的上方或左方有一个有障碍物 : 自身取非障碍物那个点的通路数
    • 自身的上、左方都是障碍物 : 自身设为0。因为左和上都走不通的话,就不存在通过本点的路径
    • 自身的上、左方都没有障碍物 : 做法同练习(14)即可

代码如下:

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int h = obstacleGrid.size();
        int w = obstacleGrid[0].size();
        if(h == 0 || w == 0 || obstacleGrid[0][0])
            return 0;

        obstacleGrid[0][0] = 1;

        // initialize
        for(int i = 1; i < w; i++)
            obstacleGrid[0][i] = obstacleGrid[0][i] ? 0 : obstacleGrid[0][i - 1];

        for(int j = 1; j < h; j++) {
            obstacleGrid[j][0] = obstacleGrid[j][0] ? 0 : obstacleGrid[j - 1][0];

            for(int i = 1; i < w; i++) {
                obstacleGrid[j][i] = obstacleGrid[j][i] ? 0 : obstacleGrid[j - 1][i] + obstacleGrid[j][i - 1];
            }
        }

        return obstacleGrid[h - 1][w - 1];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值