# leetcode--892. 三维形体的表面积

1. 三维形体的表面积
在 N * N 的网格上，我们放置一些 1 * 1 * 1 的立方体。

1 <= N <= 50
0 <= grid[i][j] <= 50

[[2]]
[[1,2],[3,4]]
[[1,0],[0,2]]
[[1,1,1],[1,0,1],[1,1,1]]
[[2,2,2],[2,1,2],[2,2,2]]
[[0,3,4,3],[4,5,0,5],[0,4,2,4],[4,0,0,2]]

class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int n = grid.size();
if (0 == n) return 0;
int ans = grid[0][0] == 0 ? 0 : grid[0][0] * 6 - 2 * (grid[0][0] - 1);
for (int j=1; j<n; j++) {
if (0 != grid[0][j]) {
int temp = grid[0][j-1] < grid[0][j] ? grid[0][j-1] : grid[0][j];
ans += grid[0][j] * 6 - 2 * (grid[0][j] - 1) - temp * 2;
}
}
for (int i=1; i<n; i++) {
for (int j=0; j<n; j++) {
if (0 != grid[i][j]) {
int temp1 = grid[i-1][j] < grid[i][j] ? grid[i-1][j] : grid[i][j];
if (0 == j) {
ans += grid[i][j] * 6 - 2 * (grid[i][j] - 1) - temp1 * 2;
} else {
int temp2 = grid[i][j-1] < grid[i][j] ? grid[i][j-1] : grid[i][j];
ans += grid[i][j] * 6 - 2 * (grid[i][j] - 1) - temp1 * 2 - temp2 * 2;
}
}
}
}
return ans;
}
};
/*32ms,8.8MB*/


class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int n = grid.size();
int ans = 0;
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
int cur = grid[i][j];
if (cur > 0) {
ans += (cur << 2) + 2;
ans -= i > 0 ? min(cur, grid[i-1][j]) << 1 : 0;
ans -= j > 0 ? min(cur, grid[i][j-1]) << 1 : 0;
}
}
}
return ans;
}
};
/*16ms,9MB*/


©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客