892. 三维形体的表面积
为保证权益,题目请参考 892. 三维形体的表面积(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int surfaceArea(vector<vector<int>> &grid) {
int ans = 0;
if (grid.empty()) {
return 0;
}
// Search for it.
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
if (grid[i][j] > 0) {
ans += 2;
//up
if (i == 0) {
ans += grid[i][j];
} else if (grid[i - 1][j] < grid[i][j]) {
ans += grid[i][j] - grid[i - 1][j];
}
//down
if (i == grid.size() - 1) {
ans += grid[i][j];
} else if (grid[i + 1][j] < grid[i][j]) {
ans += grid[i][j] - grid[i + 1][j];
}
//left
if (j == 0) {
ans += grid[i][j];
} else if (grid[i][j - 1] < grid[i][j]) {
ans += grid[i][j] - grid[i][j - 1];
}
//right
if (j == grid[0].size() - 1) {
ans += grid[i][j];
} else if (grid[i][j + 1] < grid[i][j]) {
ans += grid[i][j] - grid[i][j + 1];
}
}
}
}
return ans;
}
};
int main() {
vector<vector<int> > vec;
vector<int> row1;
row1.push_back(2);
vec.push_back((row1));
Solution so;
cout << so.surfaceArea(vec) << endl;
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
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