-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuniquePathsWithObstacles.cpp
More file actions
71 lines (66 loc) · 1.69 KB
/
uniquePathsWithObstacles.cpp
File metadata and controls
71 lines (66 loc) · 1.69 KB
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
#include <vector>
using namespace std;
class Solution
{
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid)
{
if (obstacleGrid[0][0] == 1 || obstacleGrid.back().back() == 1) return 0;
// 扩容
vector<vector<int>> res(obstacleGrid.size(),vector<int>(obstacleGrid[0].size()));
bool bShouldSetAsZero = false;
// 首先还是初始化第一横排和第一竖排
for (int i = 0;i < res[0].size();i++)
{
if (bShouldSetAsZero)
{
res[0][i] = 0;
continue;
}
if (obstacleGrid[0][i] == 1)
{
res[0][i] = 0;
bShouldSetAsZero = true;
}
else
{
res[0][i] = 1;
}
}
bShouldSetAsZero = false;
// 竖排
for (int i = 0;i < res.size();i++)
{
if (bShouldSetAsZero)
{
res[i][0] = 0;
continue;
}
if (obstacleGrid[i][0] == 1)
{
res[i][0] = 0;
bShouldSetAsZero = true;
}
else
{
res[i][0] = 1;
}
}
for (int i = 1;i < res.size();i++)
{
for (int j = 1;j < res[0].size();j++)
{
if (obstacleGrid[i][j] == 1)
{
res[i][j] = 0;
continue;
}
else
{
res[i][j] = res[i - 1][j] + res[i][j - 1];
}
}
}
return res.back().back();
}
};