Problem
NxN lattice, stacked with 1x1x1 cubes, grid[i][j] represents the number of cubes stacked on a coordinate grid, seeking the surface area of this 3D polygon.
Input: [[1,2],[3,4]]
Output:34
Ideas
Just add up the surface area of each cylinder (GRID[I][J] * 4, 4 for four sides, 2 for upper and lower Two Faces), then subtract the overlapping parts.
The overlapping portion is the smaller grid value in the adjacent column in the X-direction (or y-direction).
Code
class Solution(object): def surfaceArea(self, grid): """ :type grid: List[List[int]] :rtype: int """ s = 0 n = len(grid) for i in range(n): for j in range(n): if grid[i][j]: s += grid[i][j] * 4 + 2 if i: s -= min(grid[i][j], grid[i-1][j]) * 2 if j: s -= min(grid[i][j], grid[i][j-1]) * 2 return s
Similar topics
883. Projection area of 3D Shapes
892. Surface area of 3D Shapes