版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fuxuemingzhu/article/details/82083893
【LeetCode】892. Surface Area of 3D Shapes 解题报告(Python)
标签(空格分隔): LeetCode
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/surface-area-of-3d-shapes/description/
题目描述:
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:
Input: [[2]]
Output: 10
Example 2:
Input: [[1,2],[3,4]]
Output: 34
Example 3:
Input: [[1,0],[0,2]]
Output: 16
Example 4:
Input: [[1,1,1],[1,0,1],[1,1,1]]
Output: 32
Example 5:
Input: [[2,2,2],[2,1,2],[2,2,2]]
Output: 46
Note:
- 1 <= N <= 50
- 0 <= grid[i][j] <= 50
题目大意
所给出的数组是每个坐标下的z值,求整个空间图形的表面积。
解题方法
这个题乍一看和883. Projection Area of 3D Shapes非常相像。甚至我以为就是883题的答案乘以2就行。。但是我看到了第5个例子之后,眉头一皱发现事情并不简单。
要求整个图形的表面积,那么可以分解为求出每个立方体的表面积,然后减去重叠部分的面积。按照这个思路,就变得简单了。
如果某个位置的数值不是0,那么这个柱子的表面积是grid[i][j] * 4 + 2;
重叠部分的面积是两个柱子之间,高度最小的那个的高度.因为重叠使得两个柱子都变矮了,所以要把这个高度*2.
代码如下:
class Solution(object):
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
area = 0
n = len(grid)
for i in range(n):
for j in range(n):
if grid[i][j]: area += grid[i][j] * 4 + 2
if i: area -= min(grid[i][j], grid[i-1][j]) * 2
if j: area -= min(grid[i][j], grid[i][j-1]) * 2
return area
参考资料:无
日期
2018 年 8 月 26 日 ———— 珍爱生命,远离DD!