Projection Area of 3D Shapes

The problem asks for the total area of three projections of the grid containing cubes. Here’s the Python function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
    def projectionArea(self, grid: List[List[int]]) -> int:
        xy_projection = 0
        yz_projection = 0
        zx_projection = 0

        for i in range(len(grid)):
            zx_projection += max(grid[i])  # Max value in each row
            yz_projection += max(grid[j][i] for j in range(len(grid))) # Max value in each column

        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] > 0:
                    xy_projection += 1  # If there's a cube in the position, it adds 1 to the top projection

        return xy_projection + yz_projection + zx_projection

Explanation

The function calculates the total area of three projections:

  1. xy_projection (Top View): We look from the top. Any cell with one or more cubes will contribute 1 to the projection. Thus, we count the number of cells with value greater than 0.

  2. yz_projection (Front View): We look from the front. Each column’s contribution to the projection is the maximum value in that column. We take the maximum value from each column and sum them.

  3. zx_projection (Side View): We look from the side. Each row’s contribution to the projection is the maximum value in that row. We take the maximum value from each row and sum them.

Finally, we add the three projections to get the total area.