LeetCode 892 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.
题目分析及思路
给定一个N*N网格,在其上放置1*1*1的小方块,二维数组的值即为当前位置的高度,要求返回这样一个3D图形的表面积。可以遍历数组的每一个元素,若元素不为零,则可确定其上下两个面积算入最终的结果。然后对该位置的前后左右进行遍历,若存在元素,则若小于原元素,则返回它们的差算入最后结果,否则就不算。
python代码
class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
N = len(grid)
res = 0
for r in range(N):
for c in range(N):
if grid[r][c]:
res += 2
for nr, nc in ((r-1,c), (r+1,c), (r,c-1), (r,c+1)):
if 0 <= nr < N and 0 <= nc < N:
nval = grid[nr][nc]
else:
nval = 0
res += max(grid[r][c] - nval, 0)
return res