forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
76 lines (59 loc) · 1.76 KB
/
main.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
/// Source : https://leetcode.com/problems/surface-area-of-3d-shapes/description/
/// Author : liuyubobobo
/// Time : 2018-08-25
#include <iostream>
#include <vector>
using namespace std;
/// Ad-Hoc
/// Time Complexity: O(m*n)
/// Space Complexity: O(1)
class Solution {
private:
int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int m, n;
public:
int surfaceArea(vector<vector<int>>& grid) {
m = grid.size();
if(m == 0)
return 0;
n = grid[0].size();
int res = 0;
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++){
if(grid[i][j]){
res += 2;
for(int k = 0; k < 4; k ++){
int newX = i + d[k][0];
int newY = j + d[k][1];
if(!inArea(newX, newY))
res += grid[i][j];
else
res += max(grid[i][j] - grid[newX][newY], 0);
}
}
}
return res;
}
private:
bool inArea(int x, int y){
return x >= 0 && x < m && y >= 0 && y < n;
}
};
int main() {
vector<vector<int>> grid1 = {{2}};
cout << Solution().surfaceArea(grid1) << endl;
// 10
vector<vector<int>> grid2 = {{1, 2}, {3, 4}};
cout << Solution().surfaceArea(grid2) << endl;
// 34
vector<vector<int>> grid3 = {{1, 0}, {0, 2}};
cout << Solution().surfaceArea(grid3) << endl;
// 16
vector<vector<int>> grid4 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
cout << Solution().surfaceArea(grid4) << endl;
// 32
vector<vector<int>> grid5 = {{2, 2, 2}, {2, 1, 2}, {2, 2, 2}};
cout << Solution().surfaceArea(grid5) << endl;
// 46
return 0;
}