
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.
1def projectionArea(grid):
2 xy = 0
3 yz = 0
4 zx = 0
5 n = len(grid)
6 for i in range(n):
7 yz_max = 0
8 zx_max = 0
9 for j in range(n):
10 if grid[i][j] > 0:
11 xy += 1
12 yz_max = max(yz_max, grid[i][j])
13 zx_max = max(zx_max, grid[j][i])
14 yz += yz_max
15 zx += zx_max
16 return xy + yz + zx
17
18if __name__ == "__main__":
19 grid = [[1, 2], [3, 4]]
20 result = projectionArea(grid)
21 print(result)Python function calculates each plane's projection by tallying positive heights for XY, maximum column heights for ZX, and maximum row heights for YZ projections.
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#include <algorithm>
#include <numeric>
using namespace std;
int projectionArea(vector<vector<int>>& grid) {
int n = grid.size();
vector<int> maxRow(n, 0), maxCol(n, 0);
int xy = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] > 0) ++xy;
maxRow[i] = max(maxRow[i], grid[i][j]);
maxCol[j] = max(maxCol[j], grid[i][j]);
}
}
return xy + accumulate(maxRow.begin(), maxRow.end(), 0) + accumulate(maxCol.begin(), maxCol.end(), 0);
}
int main() {
vector<vector<int>> grid = {{1, 2}, {3, 4}};
int result = projectionArea(grid);
return result;
}Utilizes arrays to keep track of maximum values in each row and column, improving efficiency by not recalculating maximums repeatedly. Values are accumulated to find each projection area cost effectively.