Problem statement

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

Solution

Calculate first surface of all side walls, then for each two adjacent elements in grid subtract walls which they have in common and finally, add floors and ceilings.

Complexity

Time complexity will be O(n^2), space is O(n), which can be reduced to O(1).

Code

class Solution:
    def surfaceArea(self, grid):
        ans = sum(sum(row) for row in grid) * 4
        for row in chain(grid, zip(*grid)):
            ans -= 2*sum(min(x, y) for x,y in zip(row, row[1:]))
        return ans + 2*sum(v != 0 for r in grid for v in r)

Remark

See also problem 0883 Projection Area of 3D Shapes.