Problem Description
Given an n x n grid where each cell (i, j) contains a number representing the height of a tower of 1 x 1 x 1 cubes placed at that cell, determine the total area of the projections ("shadows") of these 3D shapes onto the xy, yz, and zx planes.
Key Insights
- The projection onto the xy-plane is the top view; its area is the number of non-zero cells.
- The projection onto the yz-plane (front view) is determined by the maximum value in each row.
- The projection onto the zx-plane (side view) is determined by the maximum value in each column.
- The total area is the sum of the areas of these three projections.
Space and Time Complexity
Time Complexity: O(n^2) – we iterate over all cells in the grid. Space Complexity: O(1) – aside from the input, only constant extra space is used.
Solution
The approach involves:
- Iterating over the grid to count non-zero cells for the xy projection.
- Simultaneously finding the maximum value in each row for the yz projection.
- In a separate loop, computing the maximum value in each column for the zx projection.
- Summing these three components gives the total projection area. Using simple loops ensures that the solution remains efficient with an O(n^2) time complexity. The key observation is that each projection can be computed independently based on the grid's properties.