【leetcode】63. Unique Paths II
程序员文章站
2022-06-30 22:56:11
...
题目:
思路:
思路与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. 不同路径 II
-
[leetcode]63. 不同路径 II
-
LeetCode——63.不同路径 II
-
63. Unique Paths II 动态规划
-
63. Unique Paths II 动态规划
-
【leetcode】Unique Paths II(动态规划)
-
LeetCode 63. Unique Paths II(动态规划)
-
[LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
-
【LeetCode62 Unique Paths】动态规划计算路径
-
【动态规划】LeetCode 63. Unique Paths II