-
Notifications
You must be signed in to change notification settings - Fork 0
/
0063.cpp
79 lines (75 loc) · 1.95 KB
/
0063.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
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
if (obstacleGrid[0][0] == 1)
return 0;
if (m == 1)
{
for (int j = 0; j < n; j++)
{
if (obstacleGrid[0][j] == 1) //有障碍,走不通,直接归零
return 0;
}
return 1;
}
else if (n == 1)
{
for (int i = 0; i < m; i++)
{
if (obstacleGrid[i][0] == 1)
return 0;
}
return 1;
}
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
bool ObstacleFlag = false;
for (int j = 2; j <= n; j++)
{
if(obstacleGrid[0][j-1] == 1)
ObstacleFlag = true;
if(!ObstacleFlag)
dp[1][j] = 1;
else
dp[1][j] = 0;
}
ObstacleFlag = false;
for (int i = 2; i <= m; i++)
{
if (obstacleGrid[i-1][0] == 1)
ObstacleFlag = true;
if (!ObstacleFlag)
dp[i][1] = 1;
else
dp[i][1] = 0;
}
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if (i >= 2 && j >= 2)
{
if (obstacleGrid[i - 1][j - 1] == 1)
dp[i][j] = 0;
else
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
//cout << dp[i][j] << " ";
}
//cout << endl;
}
return dp[m][n];
}
};
int main()
{
vector<vector<int>> obstacleGrid = { {0},{ 1 } };
Solution S;
S.uniquePathsWithObstacles(obstacleGrid);
return 0;
}