Description:
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.
Solution:
这是Unique Path的进化版,在路途中设置了障碍,即某些位置不能走。
标志1的位置不可以走,标号0的位置可以走,从位置[0][0]到位置[m-1][n-1]。
解决方法同理,在第一行、第一列的所有位置标记路径数为1,有障碍的位置,标记路径数为0,剩下的每个位置的路径数为它的左边和上边位置路径数之和。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] == 1){
return 0;
} else if(m == 1 && n == 1){
return 1;
}
int paths[m][n];
for(int i = 0; i < m; i++){
if(obstacleGrid[i][0] == 1){
while(i < m) {
paths[i][0] = 0;
i++;
}
break;
} else{
paths[i][0] = 1;
}
}
for(int j = 1; j < n; j++){
if(obstacleGrid[0][j] == 1){
while(j < n) {
paths[0][j] = 0;
j++;
}
break;
} else {
paths[0][j] = 1;
}
}
for(int i = 1; i < m; i++)
for(int j = 1; j < n; j++) {
if(obstacleGrid[i][j] == 1){
paths[i][j] = 0;
} else {
paths[i][j] = paths[i][j - 1] + paths[i - 1][j];
}
}
return paths[m - 1][n - 1];
}
};
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。




