Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit8c9e986

Browse files
authored
Merge pull requestneetcode-gh#2252 from ashutosh2706/add-solution
Create: 0063-unique-paths-ii.cpp
2 parents4132d8b +7b7428d commit8c9e986

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎cpp/0063-unique-paths-ii.cpp

Lines changed: 40 additions & 0 deletions
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+
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+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp