Daily Leetcode 892. Surface Area of 3D Shapes
https://leetcode.com/problems/surface-area-of-3d-shapes/
问题描述:
On a N * N
grid, we place some 1 * 1 * 1
cubes.
Each value v = grid[i][j]
represents a tower of v
cubes placed on top of grid cell (i, j)
.
Return the total surface area of the resulting shapes.
Example 1:
1 | Input: [[2]] |
Example 2:
1 | Input: [[1,2],[3,4]] |
Example 3:
1 | Input: [[1,0],[0,2]] |
Example 4:
1 | Input: [[1,1,1],[1,0,1],[1,1,1]] |
Example 5:
1 | Input: [[2,2,2],[2,1,2],[2,2,2]] |
题目分析:
这一题的输入是一个二维数组grid
,grid[i][j]
的值表示[i][j]
位置上的方块个数,所有的方块摆放在一起构成一个立方体,我们需要做的,就是计算这个立方体的面积。
由x
个方块构成的柱体的表面积大小为x*4+2
,我们将每一个位置柱体的表面积单独计算相加,得到未考虑重叠部分的面积总和S
再考虑重叠部分。重叠部分的处理也很简单,从[0][0]
位置开始遍历,计算当前柱体与下边和右边柱体重叠部分大小a
,由于在计算表面积总和时,重叠部分计算了两次,因此我们需要从S
中减去a*2
。
代码:
1 | class Solution(object): |