Skip to content

Commit 8c9e986

Browse files
authored
Merge pull request #2252 from ashutosh2706/add-solution
Create: 0063-unique-paths-ii.cpp
2 parents 4132d8b + 7b7428d commit 8c9e986

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: cpp/0063-unique-paths-ii.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
class Solution {
23+
public:
24+
int uniquePathsWithObstacles(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) return 0;
28+
vector<long long> 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+
else if(j == n-1) continue;
34+
else dp[j] = dp[j] + dp[j+1];
35+
}
36+
}
37+
return dp[0];
38+
39+
}
40+
};

0 commit comments

Comments
 (0)