Leetcode 928 Solution

This article provides solution to leetcode question 928 (surface-area-of-3d-shapes)

https://leetcode.com/problems/surface-area-of-3d-shapes

Solution

class Solution:
    def surfaceArea(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])

        ans = 0
        for i in range(m):
            for j in range(n):
                cubes = grid[i][j]

                if not cubes:
                    continue

                n_cubes = grid[i - 1][j] if i > 0 else 0
                s_cubes = grid[i + 1][j] if i < m - 1 else 0
                w_cubes = grid[i][j - 1] if j > 0 else 0
                e_cubes = grid[i][j + 1] if j < n - 1 else 0

                ans += 2
                ans += max(cubes - n_cubes, 0)
                ans += max(cubes - s_cubes, 0)
                ans += max(cubes - w_cubes, 0)
                ans += max(cubes - e_cubes, 0)

        return ans