Title description
In the N * N grid, we placed some 1 * 1 * 1 cubes aligned with the x, y, and z axes. Each value v = grid[i][j] means v cubes are stacked on cell (i, j).
Now, we look at the projections of these cubes on the xy, yz, and zx planes.
The projection is like a shadow, mapping a three-dimensional body onto a two-dimensional plane. Here, when looking at the cube from the top, front and side, we will see the "shadow".
Returns the total area of all three projections.
Example
示例 1:
输入:[[2]]
输出:5
示例 2:
输入:[[1,2],[3,4]]
输出:17
解释:
这里有该形体在三个轴对齐平面上的三个投影(“阴影部分”)。
示例 3:
输入:[[1,0],[0,2]]
输出:8
示例 4:
输入:[[1,1,1],[1,0,1],[1,1,1]]
输出:14
示例 5:
输入:[[2,2,2],[2,1,2],[2,2,2]]
输出:21
prompt
1 <= grid.length = grid[0].length <= 50
0 <= grid[i][j] <= 50
Problem solving ideas
This question is easy to handle if you understand the mathematical meaning of projection. The so-called projection is the largest area
that can be cast on a certain plane, so the projection on the xoy plane is the number of non-zero items. I used gridSize*(*gridColSize)-the number of zero items To calculate
the projection on the xoz plane is the sum of the maximum value of each sub-array.
The projection on the yoz plane is the
sum of the maximum value of each sub-array at the same position. Adding the area of the three planes can
be improved: use an array to store the maximum value, Avoiding two nested loops
Code
int projectionArea(int** grid, int gridSize, int* gridColSize){
int xyCount=gridSize*(*gridColSize);
int xzCount=0;
int yzCount=0;
for(int i=0;i<gridSize;i++){
int xMax=grid[i][0];
for(int j=0;j<*gridColSize;j++){
if(grid[i][j]==0)xyCount--;
if(grid[i][j]>xMax)xMax=grid[i][j];
}xzCount+=xMax;
}
for(int p=0;p<*gridColSize;p++){
int yMax=grid[0][p];
for(int q=0;q<gridSize;q++){
if(grid[q][p]>yMax)yMax=grid[q][p];
} yzCount+=yMax;
}return xyCount+xzCount+yzCount;
}