Leetcode解题笔记 63. Unique Paths II [Medium] 动态规划

版权声明:自由转载-非商用-非衍生-保持署名 https://blog.csdn.net/mgsweet/article/details/78733163

解题思路

其实就是要添加一步,当是障碍时,取0,其余同上一题的解题思路。

代码

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int row = obstacleGrid.size();
        int col = obstacleGrid[0].size();
        vector<vector<int>> v(row);

        for (int i = 0; i < row; i++) {
            v[i].resize(col);
        }

        if (obstacleGrid[0][0] == 1) {
            return 0;
        } else {
            v[0][0] = 1;
        }


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

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

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

        return v[row - 1][col - 1];
    }
};

猜你喜欢

转载自blog.csdn.net/mgsweet/article/details/78733163
今日推荐