-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unique_Paths_II
99 lines (85 loc) · 2.68 KB
/
Unique_Paths_II
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
/*
Unique Paths II
Follow up for "Unique Paths":
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
Note: m and n will be at most 100.
*/
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int m=obstacleGrid.size(), n=obstacleGrid[0].size();
if (obstacleGrid[m-1][n-1]==1||obstacleGrid[0][0]==1) return 0;
int numpaths[m][n];
for (int i=0; i<n; ++i)
{
if (obstacleGrid[0][i]==1)
{
for (int j=i; j<n; ++j) numpaths[0][j]=0;
break;
}
numpaths[0][i]=1;
}
for (int i=0; i<m; ++i)
{
if(obstacleGrid[i][0]==1)
{
for (int j=i; j<m; ++j) numpaths[j][0]=0;
break;
}
numpaths[i][0]=1;
}
for (int i=1; i<m; ++i)
{
for (int j=1; j<n; ++j)
{
if (obstacleGrid[i][j]==1) {numpaths[i][j]=0;continue;}
if (numpaths[i-1][j]==0) numpaths[i][j]=numpaths[i][j-1];
else if (numpaths[i][j-1]==0) numpaths[i][j]=numpaths[i-1][j];
else numpaths[i][j]=numpaths[i-1][j]+numpaths[i][j-1];
}
}
return numpaths[m-1][n-1];
}
};
REMARK:
1. IDEA: Based on the original problem Unique_Paths. We build the same m*n array to denote the number of unique paths for each position.
2. A slightly better version. Same idea, slightly different implementation.(http://yucoding.blogspot.com/2013/04/leetcode-question-117-unique-path-ii.html)
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int> > arr(m,vector<int>(n,0));
if (obstacleGrid[0][0]==1){return 0;}
arr[0][0]=1;
for (int i=1;i<m;i++){
if (obstacleGrid[i][0]!=1){
arr[i][0] = arr[i-1][0];
}
}
for (int i=1;i<n;i++){
if (obstacleGrid[0][i]!=1){
arr[0][i] = arr[0][i-1];
}
}
for (int i=1;i<m;i++){
for(int j=1;j<n;j++){
if (obstacleGrid[i][j]!=1){
arr[i][j] = arr[i][j-1] + arr[i-1][j];
}
}
}
return arr[m-1][n-1];
}
};