A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
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.
Note: m and n will be at most 100.
Example 1:
Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right
跟上一题62.Unique Paths基本类似。这道题加了障碍物,数值是1则是障碍物。
当第一个值或最后一个值为1,则直接返回0。
如果当前值为1则跳过,不是障碍物则判断左边的值和上边的值,如果不是1则加上左值和上值。最后的结果就是-1的个数,结果取-1就好了。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size();
int m = obstacleGrid[0].size();
if(obstacleGrid[0][0]==1 || obstacleGrid[n-1][m-1]==1) return 0;
obstacleGrid[0][0] = -1;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++){
if(obstacleGrid[i][j]!=1){
if(j-1>=0&&obstacleGrid[i][j-1]!=1)
obstacleGrid[i][j] += obstacleGrid[i][j-1];
if(i-1>=0&&obstacleGrid[i-1][j]!=1)
obstacleGrid[i][j] += obstacleGrid[i-1][j];
}
}
return -obstacleGrid[n-1][m-1];
}
};
参考这篇文章,点我。