https://leetcode.com/problems/unique-paths-ii/description/
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
中文翻譯:
和之前的unique path題一樣,問你起點道終點有幾種方法。
不過這次的矩陣上有些格子不能走。
[solution]
Dynamic Programming.
The answer of (x,y) = answer of (x,y-1) + answer of (x-1,y).
But if (x,y) is an obstacle, answer of (x,y) = 0.
The solution is the same with previous problem.
But there are some obstacles on the grid.
So the answer of those obstacles are '0', which means no way to go to those obstacles.
Let's write code~
We only need to modify one line for checking if it's a obstacle.
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m=obstacleGrid.size();
int n=obstacleGrid[0].size();
vector<vector<int>> matrix(2, vector<int>(n+1,0));
matrix[1][0]=1;
for(int r=1;r<=m;r++){
for(int c=1;c<=n;c++){
matrix[r%2][c]=(obstacleGrid[r-1][c-1]==1) ? 0 : matrix[r%2][c-1] + matrix[(r-1)%2][c];
}
if(r==1) matrix[1][0]=0;
}
return matrix[m%2][n];
}
};