2025-08-01 12:30:00 +0000 UTC

Surface Area of 3D Shapes

Code

class Solution:
    def surfaceArea(self, grid: list[list[int]]) -> int:
        length = len(grid)
        res = 0
        adj_delta = (
            (-1, 0), (1, 0), (0, -1), (0, 1)
        )
        for row in range(length):
            for col in range(length):
                height = grid[row][col]
                if height == 0:
                    continue
                res += 2
                for row_delta, col_delta in adj_delta:
                    adj_row, adj_col = row + row_delta, col + col_delta
                    if 0 <= adj_row < length and 0 <= adj_col < length:
                        adj_height = grid[adj_row][adj_col]
                    else:
                        adj_height = 0
                    if height > adj_height:
                        res += grid[row][col] - adj_height
        return res