【leetcode】 Unique Path ||(easy)

时间:2021-09-16 05:00:53

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.

思路:跟Unique Paths差不多,就是把有障碍的地方方法数变成0,注意左上角为障碍的情况

class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
if(obstacleGrid.empty())
{
return ;
}
vector<vector<int>> ways(obstacleGrid.size(), vector<int>(obstacleGrid[].size(),));
if(obstacleGrid[][] == )
{
ways[][] = ;
}
for(int c = ; c < obstacleGrid[].size(); c++)
{
ways[][c] = (obstacleGrid[][c] == ) ? : ways[][c - ];
}
for(int r = ; r < obstacleGrid.size(); r++)
{
ways[r][] = (obstacleGrid[r][] == ) ? : ways[r - ][];
}
for(int i = ; i < obstacleGrid.size(); i++)
{
for(int j = ; j < obstacleGrid[].size(); j++)
{
ways[i][j] = (obstacleGrid[i][j] == ) ? : ways[i - ][j] + ways[i][j - ];
}
}
return ways[obstacleGrid.size() - ][obstacleGrid[].size() - ];
}
};