首页 > 其他 > 详细

Unique Paths II

时间:2017-09-02 20:22:30      阅读:253      评论:0      收藏:0      [点我收藏+]

注意一个容易犯的错误:判断obstacleGrid是否为1时,else那部分不能少。因为如果不加,就会默认把那些值设置为0。

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

 

Unique Paths II

原文:http://www.cnblogs.com/ymjyqsx/p/7467591.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!