给你一个 n * n 的网格 grid ,上面放置着一些 1 x 1 x 1 的正方体。每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。
放置好正方体后,任何直接相邻的正方体都会互相粘在一起,形成一些不规则的三维形体。
请你返回最终这些形体的总表面积。
注意:每个形体的底面也需要计入表面积中。
You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).
After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.
Return the total surface area of the resulting shapes.
Note: The bottom face of each shape counts toward its surface area.
示例 1:
输入:grid = [[1,2],[3,4]]
输出:34
示例 2:
输入:grid = [[1,1,1],[1,0,1],[1,1,1]]
输出:32
示例 3:
输入:grid = [[2,2,2],[2,1,2],[2,2,2]]
输出:46
-
对每一项进行遍历,当grid[i][j]值存在时才会有加有减
-
grid[i][j]的表面积(没有去除左右重叠部分) 2 + 4 * grid[i][j]
-
只需要减掉右边和上面的 重叠部分*2(重叠部分取两个相邻的最小值)
var surfaceArea = function (grid) {
let len = grid.length
let sum = 0
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
let v = grid[i][j]
if (!v) {
continue
}
sum += 2 + 4 * v
if (i - 1 >= 0) {
sum -= Math.min(grid[i][j], grid[i - 1][j]) * 2
}
if (j + 1 < len) {
sum -= Math.min(grid[i][j], grid[i][j + 1]) * 2
}
}
}
return sum
};
leetcode:https://leetcode.cn/problems/surface-area-of-3d-shapes/