You are given an n x n
grid represented by a 2D array grid
. Each value grid[i][j]
represents the height of a 3D shape placed on that i-th
row and j-th
column. We need to return the projection area of these 3D shapes.
The projection area of a 3D shape on the xy-plane, yz-plane, and zx-plane is described as follows:
xy-plane
: The number of cells in the grid that contain a positive integer.yz-plane
: The maximum value in each row.zx-plane
: The maximum value in each column.The total projection area is the sum of the areas on the xy-plane, yz-plane, and zx-plane.
grid[i][j]
take?
n
be?
n
can be up to 50 in competitive programming scenarios on LeetCode.To solve this problem efficiently, we will iterate through the grid once to compute the areas for the xy-plane, yz-plane, and zx-plane:
def projectionArea(grid):
n = len(grid)
xy_area = 0 # Projection on xy-plane
yz_area = 0 # Projection on yz-plane (rows)
zx_area = 0 # Projection on zx-plane (columns)
# To compute zx_area, we need to store the max values for each column
max_in_columns = [0] * n
for i in range(n):
max_in_row = 0
for j in range(n):
height = grid[i][j]
if height > 0:
xy_area += 1
max_in_row = max(max_in_row, height)
max_in_columns[j] = max(max_in_columns[j], height)
yz_area += max_in_row
zx_area = sum(max_in_columns)
return xy_area + yz_area + zx_area
The overall time complexity of this solution is O(n^2) because we are iterating through each cell of the grid once (a total of n^2 cells).
By summing these three areas, we get the total projection area of the 3D shapes from all perspectives.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?