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
分析
题目的意思是:求给定的方块的面积。顶部和底部的面积很好求,如果碰见方块,re s加上2就行了,对于其他面的面积,要看相邻的方块,如果四周乡邻的方块比当前的方块矮,就贡献了面积,贡献的面积为:max(grid[i][j]-t,0) ,t为四周的方块的高度大小。如果弄懂了这个就好办了。
代码
class Solution:
def surfaceArea(self, grid: List[List[int]]) -> int:
res=0
n=len(grid)
for i in range(n):
for j in range(n):
if(grid[i][j]):
res+=2
arr=[[i-1,j],[i+1,j],[i,j-1],[i,j+1]]
for r,c in arr:
if(r>=0 and r<n and c>=0 and c<n):
t=grid[r][c]
else:
t=0
res+=max(grid[i][j]-t,0)
return res