与上一个题目类似,只是矩阵中有些障碍,那么任何障碍点的到达路径数为0,因此我们依然只需要一个一维数组保存上层每个位置的路径数,只是当遇到障碍时要置0,使用一维数组的思想在上一篇博客中Unique Paths。接下来直接上代码
#define MaxSize 120
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> >& obstacleGrid) {
int i,j;
int path[MaxSize];
if(obstacleGrid.size()==1) //数组只有一行
for(int i=0;i<obstacleGrid[0].size();i++)
if(obstacleGrid[0][i] == 1)
return 0;
if(obstacleGrid[0].size()==1) //数组只有一列
for(int i=0;i<obstacleGrid.size();i++)
if(obstacleGrid[i][0] == 1)
return 0;
bool flag = 0;
for(i=0;i<obstacleGrid[0].size();i++){ //初始化path数组
if(flag)
path[i] = 0;
else if(obstacleGrid[0][i] == 1){
path[i] = 0;
flag = 1;
}
else
path[i] = 1;
}
for(i=1;i<obstacleGrid.size();i++){
if(obstacleGrid[i][0] == 1)
path[0] = 0;
for(j=1;j<obstacleGrid[0].size();j++){
if(obstacleGrid[i][j] == 1) //遇到障碍,置0
path[j] = 0;
else
path[j] += path[j-1];
}
}
return path[obstacleGrid[0].size()-1];
}
};
运行时间