欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【leetcode】63. Unique Paths II

程序员文章站 2022-06-30 22:56:11
...

题目:
【leetcode】63. Unique Paths II


思路:
思路与62. Unique Paths一样,用动态规划,比较简单。唯一的区别是,这里把障碍所在位置的dp[i][j]设置成0即可。


代码实现:
注意:dp数组之所以用long long的形式是因为在相加时会发生signed int溢出。

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        long long dp[100][100];
        int rows = obstacleGrid.size();
        int cols = obstacleGrid[0].size();
        
        bool has_obs = false;
        for (int i = 0; i < rows; ++i){
            if (obstacleGrid[i][0] == 1){
                has_obs = true;
            }
            if (has_obs == true){
                dp[i][0] = 0;
            }else{
                dp[i][0] = 1;
            }
        }
        has_obs = false;
        for (int i = 0; i < cols; ++i){
            if (obstacleGrid[0][i] == 1){
                has_obs = true;
            }
            if (has_obs == true){
                dp[0][i] = 0;
            }else{
                dp[0][i] = 1;
            }
        }
        
        for (int i = 1; i < rows; ++i){
            for (int j = 1; j < cols; ++j){
                dp[i][j] = 0;
                if (obstacleGrid[i][j] == 0){
                    if (i-1 >= 0){
                        dp[i][j] += dp[i-1][j];
                    }
                    if (j-1 >= 0){
                        dp[i][j] += dp[i][j-1];
                    }
                }
            }
        }
        
        return dp[rows-1][cols-1];
    }
};

【leetcode】63. Unique Paths II