跳到主要内容

892.三维形体的表面积

链接:892.三维形体的表面积
难度:Easy
标签:几何、数组、数学、矩阵
简介:请你返回最终这些形体的总表面积。

题解 1 - cpp

  • 编辑时间:2022-03-22
  • 执行用时:4ms
  • 内存消耗:9MB
  • 编程语言:cpp
  • 解法介绍:对每一块的四边进行统计。
int dirs[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int n = grid.size(), ans = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
int cnt = grid[row][col];
if (cnt == 0) continue;
ans += 2;
for (int i = 0; i < 4; i++) {
int nrow = row + dirs[i][0], ncol = col + dirs[i][1];
if (nrow < 0 || nrow >= n || ncol < 0 || ncol >= n) {
ans += cnt;
continue;
}
int ncnt = grid[nrow][ncol];
if (ncnt < cnt) ans += cnt - ncnt;
}
}
}
return ans;
}
};