【leetcode】892. Surface Area of 3D Shapes

题目如下:

解题思路:对于v = grid[i][j],其表面积为s = 2 + v*4 。接下来只要在判断其相邻四个方向有没有放置立方体,有的话减去重合的面积即可。

代码如下:

class Solution(object):
    def surfaceArea(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        res = 0
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == 0:
                    continue
                area = 2 + 4 * grid[i][j]
                if i-1 >= 0:
                    area -= min(grid[i-1][j],grid[i][j])
                if j-1 >= 0:
                    area -= min(grid[i][j],grid[i][j-1])
                if i + 1 < len(grid):
                    area -= min(grid[i][j],grid[i+1][j])
                if j + 1 < len(grid[i]):
                    area -= min(grid[i][j],grid[i][j+1])
                res += area
        return res

 

posted @ 2018-09-01 10:00  seyjs  阅读(378)  评论(0编辑  收藏  举报