-
Notifications
You must be signed in to change notification settings - Fork 5
/
LC_63_UniquePathsII.cpp
99 lines (83 loc) · 2.46 KB
/
LC_63_UniquePathsII.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
https://leetcode.com/problems/unique-paths-ii/
63. Unique Paths II
*/
class Solution {
public:
int uniquePathsWithObstacles_1(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
return 0;
obstacleGrid[0][0] = 1;
for(int r=1; r<m; r++)
{
if(obstacleGrid[r][0]==0)
obstacleGrid[r][0] = obstacleGrid[r-1][0] ;
else
obstacleGrid[r][0] = 0;
}
for(int c=1; c<n; c++)
{
if(obstacleGrid[0][c]==0)
obstacleGrid[0][c] = obstacleGrid[0][c-1];
else
obstacleGrid[0][c] = 0;
}
for(int r=1; r<m; r++)
{
for(int c=1; c<n; c++)
{
if(obstacleGrid[r][c]==0)
obstacleGrid[r][c] = obstacleGrid[r-1][c] + obstacleGrid[r][c-1];
else
obstacleGrid[r][c]=0;
}
}
// for(int r=0; r<m; r++)
// {
// for(int c=0; c<n; c++)
// {
// cout<< obstacleGrid[r][c]<<" ";
// }
// cout<<endl;
// }
return obstacleGrid[m-1][n-1];
}
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)
return 0;
vector<vector<int>> dp(2, vector<int>(n, 0));
dp[0][0] = 1;
int ind=0;
for(int c=1; c<n; c++)
{
if(obstacleGrid[0][c]==0)
dp[0][c] = dp[0][c-1] ;
else
break;
}
for(int r=1; r<m; r++)
{
ind = 1-ind;
for(int c=0; c<n; c++)
{
if(obstacleGrid[r][c]==0)
dp[ind][c] = dp[1-ind][c] + ((c==0) ? 0 : dp[ind][c-1]);
else
dp[ind][c] = 0;
}
}
// for(int r=0; r<2; r++)
// {
// for(int c=0; c<n; c++)
// {
// cout<< dp[r][c]<<" ";
// }
// cout<<endl;
// }
return dp[ind][n-1];
}
};