Projection Area of 3D Shapes Solution in Java

Explore Solutions in Other Languages

Problem Description

Ah, the Projection Area of 3D Shapes! It’s like trying to figure out how much space your collection of oddly shaped fruit takes up on your kitchen counter. Imagine you have a bunch of cubes stacked up, and you want to know how much of that mess you can actually see from above, the sides, and the front. Spoiler alert: it’s not as straightforward as it sounds!

In this problem, you are given a 2D grid representing a 3D shape where each cell contains a positive integer. This integer represents the height of the shape at that position. Your task is to calculate the total projection area of these shapes when viewed from three different perspectives: top, front, and side.

So, if you’ve ever tried to stack your laundry and wondered how much of it is actually visible from the hallway, you’ll get the gist of this problem!

Code Solution


class Solution {
  public int projectionArea(int[][] grid) {
    int ans = 0;

    for (int i = 0; i < grid.length; ++i) {
      int maxOfRow = 0;
      int maxOfCol = 0;
      for (int j = 0; j < grid.length; ++j) {
        maxOfRow = Math.max(maxOfRow, grid[i][j]);
        maxOfCol = Math.max(maxOfCol, grid[j][i]);
        if (grid[i][j] > 0)
          ++ans;
      }
      ans += maxOfRow + maxOfCol;
    }

    return ans;
  }
}

Approach

The approach taken in this solution is quite straightforward. We iterate through the grid to calculate three different projections:

  1. Top Projection: Count all non-zero cells, as they contribute to the top view.
  2. Front Projection: For each row, find the maximum height to determine how much is visible from the front.
  3. Side Projection: For each column, find the maximum height to determine how much is visible from the side.

By summing these three projections, we get the total projection area.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(N2), where N is the length of the grid. We traverse the grid multiple times.
Space Complexity O(1), as we are using a constant amount of space for variables.

Real-World Example

Imagine you’re at a fruit market, and you see a pile of apples, oranges, and bananas stacked in a chaotic manner. You want to know how many fruits you can see from above (top view), how many you can see from the front (front view), and how many you can see from the side (side view). This problem is akin to calculating the projection area of that fruit pile!

Similar Problems

If you enjoyed this problem, you might also like these:

  • 2-Sum Solution in Java
  • 3-Sum Solution in Java
  • 4-Sum Solution in Java