关闭

102. Unique Paths II

88人阅读 评论(0) 收藏 举报
分类:

-63. Unique Paths II My Submissions QuestionEditorial Solution
Total Accepted: 67444 Total Submissions: 228395 Difficulty: 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.

[
[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.
难度:在无障碍的基础上进行小改动即可,就是如果当前为障碍点,则
其路径数设为0,如果不是障碍点,则按之前的公式计算

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:752265次
    • 积分:9427
    • 等级:
    • 排名:第1910名
    • 原创:197篇
    • 转载:157篇
    • 译文:2篇
    • 评论:12条
    最新评论