63. Unique Paths II

来源:互联网 发布:淘宝能修改实名认证吗 编辑:程序博客网 时间:2024/06/03 21:36

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.

Note: m and n will be at most 100.

这道题还是直接计算每一步的走法然后相加就好,绕过障碍
代码如下:

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {        if(obstacleGrid.size()==0||obstacleGrid[0].size()==0||obstacleGrid[0][0]==1||obstacleGrid[obstacleGrid.size()-1][obstacleGrid[0].size()-1]==1)return 0;        int ans[obstacleGrid[0].size()];        for(int i=0;i<obstacleGrid[0].size();i++){            ans[i]=0;        }        ans[0]=1;        for(int i=0;i<obstacleGrid.size();i++){            if(obstacleGrid[i][0]==1)ans[0]=0;            for(int j=1;j<obstacleGrid[0].size();j++){                if(obstacleGrid[i][j]==0)ans[j]=ans[j-1]+ans[j];                else{                    ans[j]=0;                }            }        }        return ans[obstacleGrid[0].size()-1];        }};
原创粉丝点击