63. Unique Paths II

题目

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.

[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.

分析

和第62题基本一样,不同的是在初始化时要将障碍处的路径数置为0,且在推导的时候跳过这些位置。
而且也要推导最后两行。

实现

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        if(obstacleGrid.empty() || obstacleGrid[0].empty()) return 0;
        int m=obstacleGrid.size(), n=obstacleGrid[0].size();
        int dp[m][n];
        dp[m-1][n-1] = 1;
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
                if(obstacleGrid[i][j])
                    dp[i][j] = 0;
        for(int i=m-2; i>=0; i--)
            if(!obstacleGrid[i][n-1]) dp[i][n-1] = dp[i+1][n-1];
        for(int i=n-2; i>=0; i--)
            if(!obstacleGrid[m-1][i]) dp[m-1][i] = dp[m-1][i+1];
        for(int i=m-2; i>=0; i--)
            for(int j=n-2; j>=0; j--)
                if(!obstacleGrid[i][j])
                    dp[i][j] = dp[i+1][j] + dp[i][j+1];
        return dp[0][0];
    }
};

思考

做这种题的时候要非常注意,条件增加时变化了的情况。如果继续沿用之前的那种初始化最后一行和最后一列为1的情况就会出现问题,改成由后一个推导才可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Follow up for "Unique Paths":Now consider if some obstacl...
    ShutLove阅读 197评论 0 0
  • Follow up for "Unique Paths":Now consider if some obstacl...
    HalcyonMoon阅读 296评论 0 0
  • Follow up for "Unique Paths": Now consider if some obstac...
    Jeanz阅读 245评论 0 0
  • Description Follow up for "Unique Paths": Now consider if...
    Nancyberry阅读 294评论 0 0
  • 10点的时候收到好友的回复,因为长期的空白她面临词穷的困境所以无法准时给我一篇文稿,我玩笑式的回复好友,不会第二天...
    素与舒阅读 290评论 0 1