|
| 1 | +/* |
| 2 | +
|
| 3 | +Given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). |
| 4 | +The robot can only move either down or right at any point in time. An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle. |
| 5 | +
|
| 6 | +Return the number of possible unique paths that the robot can take to reach the bottom-right corner. |
| 7 | +
|
| 8 | +Example. obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] |
| 9 | + There is one obstacle in the middle of the 3x3 grid above. |
| 10 | + There are two ways to reach the bottom-right corner: |
| 11 | + 1. Right -> Right -> Down -> Down |
| 12 | + 2. Down -> Down -> Right -> Right |
| 13 | + So, the number of unique paths the robot can take is 2. Hence we return 2 as our answer. |
| 14 | +
|
| 15 | +
|
| 16 | +Time: O(m * n) |
| 17 | +Space: O(n) |
| 18 | +
|
| 19 | +*/ |
| 20 | + |
| 21 | + |
| 22 | +classSolution { |
| 23 | +public: |
| 24 | +intuniquePathsWithObstacles(vector<vector<int>>& grid) { |
| 25 | + |
| 26 | +int m = grid.size(), n = grid[0].size(); |
| 27 | +if(grid[m-1][n-1] ==1 || grid[0][0] ==1)return0; |
| 28 | + vector<longlong>dp(n); |
| 29 | + dp[n-1] =1; |
| 30 | +for(int i=m-1; i>=0; i--) { |
| 31 | +for(int j=n-1; j>=0; j--) { |
| 32 | +if(grid[i][j] ==1) dp[j] =0; |
| 33 | +elseif(j == n-1)continue; |
| 34 | +else dp[j] = dp[j] + dp[j+1]; |
| 35 | + } |
| 36 | + } |
| 37 | +return dp[0]; |
| 38 | + |
| 39 | + } |
| 40 | +}; |