Surface Area of 3D Shapes

Here’s a way to calculate the total surface area of the resulting 3D shapes formed by the cubes placed on the grid.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
    def surfaceArea(self, grid: List[List[int]]) -> int:
        # Initialize the surface area variable
        surface_area = 0
        n = len(grid)

        # Iterate through each cell of the grid
        for i in range(n):
            for j in range(n):
                # If there are cubes in this cell, calculate the surface area
                if grid[i][j] > 0:
                    # Add the top and bottom surfaces
                    surface_area += 2

                    # Add the surface area for the sides
                    for x, y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
                        ni, nj = i + x, j + y
                        # If adjacent cell is within bounds
                        if 0 <= ni < n and 0 <= nj < n:
                            neighbour = grid[ni][nj]
                        else:
                            neighbour = 0

                        # Calculate the exposed surface for this side
                        surface_area += max(grid[i][j] - neighbour, 0)

        return surface_area

Here’s how this code works:

  • We iterate through each cell (i, j) of the grid.
  • For each cell, if it contains cubes (grid[i][j] > 0), we add 2 to the surface area for the top and bottom faces.
  • Then, we iterate through the four possible directions (1, 0), (-1, 0), (0, 1), (0, -1) to check the adjacent cells. We calculate the difference between the current cell’s cube count and the neighbor’s cube count to find the exposed surface area for that side. If the adjacent cell is out of bounds, we consider the neighbor’s cube count as 0.
  • We sum up all these contributions to get the total surface area for the grid.