Leetcode 883. Projection Area of 3D Shapes
In a 2D grid of size n x n
, there are n x n
3D shapes. Each shape is represented by an integer value grid[i][j]
where grid[i][j]
indicates the height of the 3D shape at position (i, j)
.
The projection of these shapes onto the xy-plane, yz-plane, and zx-plane are outlines that form shadows. We need to calculate the total area of these projections.
Your task is to write a function that calculates the total area of these projections.
grid[i][j]
?n x n
?grid[i][j]
) be zero?Here is a function to solve the problem:
#include <vector>
#include <algorithm>
using namespace std;
int projectionArea(vector<vector<int>>& grid) {
int n = grid.size();
int xyArea = 0, yzArea = 0, zxArea = 0;
// Iterate through each row and column
for (int i = 0; i < n; ++i) {
int maxRow = 0;
int maxCol = 0;
for (int j = 0; j < n; ++j) {
// For xy projection, count all non-zero heights
if (grid[i][j] > 0) {
xyArea++;
}
// For zx projection, find the maximum height in the row
maxRow = max(maxRow, grid[i][j]);
// For yz projection, find the maximum height in the column
maxCol = max(maxCol, grid[j][i]);
}
zxArea += maxRow;
yzArea += maxCol;
}
return xyArea + yzArea + zxArea;
}
Finally, sum all three areas to get the total projection area.
n x n
grid to compute the areas of all three projections.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?