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
2
Input: [[2]]
Output: 10

Example 2:

1
2
Input: [[1,2],[3,4]]
Output: 34

Example 3:

1
2
Input: [[1,0],[0,2]]
Output: 16

Example 4:

1
2
Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 32

Example 5:

1
2
Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 46

题目分析:

这一题的输入是一个二维数组gridgrid[i][j]的值表示[i][j]位置上的方块个数,所有的方块摆放在一起构成一个立方体,我们需要做的,就是计算这个立方体的面积。

x个方块构成的柱体的表面积大小为x*4+2,我们将每一个位置柱体的表面积单独计算相加,得到未考虑重叠部分的面积总和S再考虑重叠部分。重叠部分的处理也很简单,从[0][0]位置开始遍历,计算当前柱体与下边和右边柱体重叠部分大小a,由于在计算表面积总和时,重叠部分计算了两次,因此我们需要从S中减去a*2

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
N, res = len(grid), 0
for i in range(N):
for j in range(N):
if grid[i][j]:
res = res + grid[i][j]*4 + 2
if i < N - 1:
res = res - min(grid[i+1][j], grid[i][j])*2
if j < N - 1:
res = res - min(grid[i][j+1], grid[i][j])*2
return res