Leetcode 883. Projection Area of 3D Shapes
You are given an array of n
n
integers grid
where grid[i][j] represents the height of a 3D shape located at position (i, j). We need to calculate the projection area of these 3D shapes onto the xy-plane, yz-plane, and zx-plane.
Return the total projection area of the 3D shapes.
Example:
Input: grid = [[1,2],[3,4]]
Output: 17
Explanation: Here are the three projections ("shadows") of the shape made with each axis.
To solve the problem, we need to calculate the projection areas on three planes:
Here is how to implement this in Java:
public class Solution {
public int projectionArea(int[][] grid) {
int n = grid.length;
int xy = 0, yz = 0, zx = 0;
for (int i = 0; i < n; i++) {
int maxRow = 0;
int maxCol = 0;
for (int j = 0; j < n; j++) {
// xy-plane projection: count if there's a tower at grid[i][j]
if (grid[i][j] > 0) xy++;
// yz-plane projection: max height in row i
maxRow = Math.max(maxRow, grid[i][j]);
// zx-plane projection: max height in column j
maxCol = Math.max(maxCol, grid[j][i]);
}
yz += maxRow;
zx += maxCol;
}
return xy + yz + zx;
}
}
This approach efficiently calculates the projection areas by iterating through the grid in a structured manner, ensuring we account for all three projections correctly.
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?