
Sponsored
Sponsored
In this approach, we calculate each plane's projection separately, then sum them up for the total projection area. For the XY-plane projection, we count every cell with a positive value. For the YZ-plane, we determine the maximum value in each row (representing the view from the side). For the ZX-plane, we find the maximum value in each column (representing the view from the front).
Time Complexity: O(n^2) since we traverse each grid element once.
Space Complexity: O(1) since we use no additional space proportional to the input size.
1#include <vector>
2#include <algorithm>
3using namespace std;
4
5int projectionArea(vector<vector<int>>& grid) {
6 int xy = 0, yz = 0, zx = 0;
7 int n = grid.size();
8 for (int i = 0; i < n; ++i) {
9 int yz_max = 0;
10 for (int j = 0; j < n; ++j) {
11 if (grid[i][j] > 0) xy++;
12 yz_max = max(yz_max, grid[i][j]);
13 zx = max(zx, grid[j][i]);
14 }
15 yz += yz_max;
16 }
17 return xy + yz + zx;
18}
19
20int main() {
21 vector<vector<int>> grid = {{1, 2}, {3, 4}};
22 int result = projectionArea(grid);
23 return result;
24}This C++ solution computes projections for each of the three views independently by iterating over the grid elements and tracking necessary maximum values for column and row.
This approach improves upon the earlier method by precomputing the maximum values in each row and column before calculating the projections. By storing these values in separate arrays, it helps avoid repeatedly calculating max values within nested loops for each axis projection.
Time Complexity: O(n^2) to fill the grid, row, and column arrays.
Space Complexity: O(n) to store column maximums.
1
Python's solution involves using additional arrays to hold maximum values for rows and columns, ensuring these are not recalculated repeatedly as the grid is traversed.