# 63. Unique Paths II

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

# Solution

Approach 1: DP.

# Code (Python)

Approach 1:

    def uniquePathsWithObstacles(self, grid: List[List[int]]) -> int:
        paths = [1 if grid[0][0] == 0 else 0]
        for i in range(1, len(grid[0])):
            if grid[0][i] == 1:
                paths.append(0)
            else:
                paths.append(paths[i-1])
        for i in range(1, len(grid)):
            for j in range(len(grid[0])):
                if j == 0:
                    paths[j] = 0 if grid[i][j] == 1 else paths[j]
                else:
                    paths[j] = paths[j] + paths[j-1] if grid[i][j] == 0 else 0
        return paths[-1]

# Code (C++)

Approach 1:

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int rowSize = obstacleGrid.size();
        if (rowSize == 0)
            return 0;
        int colSize = obstacleGrid[0].size();
        long paths[rowSize][colSize];
        paths[rowSize-1][colSize-1] = obstacleGrid[rowSize-1][colSize-1] ? 0 : 1;
        for (int i = rowSize - 1; i >= 0; --i)
        {
            for (int j = colSize - 1; j >= 0; --j)
            {
                if (i < rowSize - 1|| j < colSize - 1)
                    paths[i][j] = 0;
                if (obstacleGrid[i][j])
                    continue;
                if (i < rowSize - 1)
                    paths[i][j] += paths[i+1][j];
                if (j < colSize - 1)
                    paths[i][j] += paths[i][j+1];
            }
        }
        return paths[0][0];
    }
};