[LeetCode&Python] Problem 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.
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 <= 500 <= grid[i][j] <= 50
class Solution(object):
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
allside=0
overlap=0
for i, v in enumerate(grid):
for j, z in enumerate(v):
if z==0:
continue
allside+=4*z+2
if i!=0:
overlap+=min(z,grid[i-1][j])
if i!=len(grid)-1:
overlap+=min(z,grid[i+1][j])
if j!=0:
overlap+=min(z,grid[i][j-1])
if j!=len(grid[0])-1:
overlap+=min(z,grid[i][j+1])
return allside-overlap
浙公网安备 33010602011771号