63. 不同路径 II
为保证权益,题目请参考 63. 不同路径 II(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
if (obstacleGrid.size() == 0 || obstacleGrid[0].size() == 0) {
return 0;
}
if (obstacleGrid.size() == 1 && obstacleGrid[0].size() == 1) {
return !obstacleGrid[0][0];
}
if(obstacleGrid[0][0] > 0 || obstacleGrid[obstacleGrid.size() - 1][obstacleGrid[0].size() - 1] > 0){
return 0;
}
obstacleGrid[0][0] = -1;
for (int i = 1; i < obstacleGrid.size(); i++) {
if (obstacleGrid[i][0] == 0) {
obstacleGrid[i][0] = obstacleGrid[i - 1][0] > 0 ? 0 : obstacleGrid[i - 1][0];
}
}
for (int i = 1; i < obstacleGrid[0].size(); i++) {
if (obstacleGrid[0][i] == 0) {
obstacleGrid[0][i] = obstacleGrid[0][i - 1] > 0 ? 0 : obstacleGrid[0][i - 1];
}
}
// for (int i = 0; i < obstacleGrid.size(); i++) {
// for (int j = 0; j < obstacleGrid.size(); j++) {
// cout << obstacleGrid[i][j] << " ";
// }
// cout << endl;
// }
for (int i = 1; i < obstacleGrid.size(); i++) {
for (int j = 1; j < obstacleGrid.size(); j++) {
if (obstacleGrid[i][j] == 0) {
obstacleGrid[i][j] += obstacleGrid[i - 1][j] > 0 ? 0 : obstacleGrid[i - 1][j];
obstacleGrid[i][j] += obstacleGrid[i][j - 1] > 0 ? 0 : obstacleGrid[i][j - 1];
}
}
}
// for (int i = 0; i < obstacleGrid.size(); i++) {
// for (int j = 0; j < obstacleGrid.size(); j++) {
// cout << obstacleGrid[i][j] << " ";
// }
// cout << endl;
// }
return -obstacleGrid[obstacleGrid.size() - 1][obstacleGrid[0].size() - 1];
}
};
int main() {
return 0;
}
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
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