892.三维形态的表面积(javascript)892.SurfaceAreaof3DShapes
原创给你一个 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/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除