algoadvance

Leetcode 883. Projection Area of 3D Shapes

Problem Statement

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:

Example:
Input: grid = [[1,2],[3,4]]
Output: 17
Explanation: Here are the three projections ("shadows") of the shape made with each axis.

Clarifying Questions

Strategy

To solve the problem, we need to calculate the projection areas on three planes:

  1. xy-plane: This is simply the count of cells with non-zero heights.
  2. yz-plane: For each row, take the maximum height and sum them up.
  3. zx-plane: For each column, take the maximum height and sum them up.

Here is how to implement this in Java:

Code

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;
    }
}

Time Complexity

This approach efficiently calculates the projection areas by iterating through the grid in a structured manner, ensuring we account for all three projections correctly.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI