Projection Area Of 3D Shapes Problem
Description
LeetCode Problem 883.
You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).
We view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.
Example 1:
Input: grid = [[1,2],[3,4]]
Output: 17
Explanation: Here are the three projections ("shadows") of the shape made with each axis-aligned plane.
Example 2:
Input: grid = [[2]]
Output: 5
Example 3:
Input: grid = [[1,0],[0,2]]
Output: 8
Example 4:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]]
Output: 14
Example 5:
Input: grid = [[2,2,2],[2,1,2],[2,2,2]]
Output: 21
Constraints:
- n == grid.length
- n == grid[i].length
- 1 <= n<= 50
- 0 <= grid[i][j] <= 50
Solution
Approach: Add Up the Three Shadows
Each of the three views can be counted on its own:
- Top view (xy-plane): every cell with at least one cube casts a 1 × 1 shadow, so this view is the number of cells with
grid[i][j] > 0. - Front view: looking along a row, the towers in that row hide behind each other, and only the tallest one shows. So this view is the sum of the maximum of each row.
- Side view: the same idea for columns: the sum of the maximum of each column.
The answer is the sum of the three. One pass is enough: for each i, scan j and track the maximum of row i (grid[i][j]) and of column i (grid[j][i]) at the same time, while counting the non-empty cells.
The easy mistake is the top view: it counts cells, not cubes. A tower of height 5 still makes a shadow of area 1 from above, and an empty cell makes none.
Example 1, [[1,2],[3,4]]: top = 4, row maxima = 2 + 4 = 6, column maxima = 3 + 4 = 7, total 17.
Complexity: O(n2) time and O(1) space, where n is the size of the grid.
class Solution:
def projectionArea(self, grid: List[List[int]]) -> int:
n = len(grid)
area = 0
for i in range(n):
row_max = 0 # tallest tower in row i
column_max = 0 # tallest tower in column i
for j in range(n):
if grid[i][j] > 0:
area += 1 # top view: one unit per non-empty cell
row_max = max(row_max, grid[i][j])
column_max = max(column_max, grid[j][i])
area += row_max + column_max # the two side views
return area
Now write it from memory
Close the write-up and solve it yourself against the tests.