883. Projection Area of 3D Shape
2018-10-04 本文已影响0人
美不胜收oo
描述
On a N * N grid, we place some 1 * 1 * 1 cubes that are axis-aligned with the x, y, and z axes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell (i, j).
Now we view the projection of these cubes onto the xy, yz, and zx planes.
A projection is like a shadow, that maps our 3 dimensional figure to a 2 dimensional plane.
Here, we are viewing the "shadow" when looking at the cubes from the top, the front, and the side.
Return the total area of all three projections.
![](https://img.haomeiwen.com/i10118984/5265bd2c06f38f05.png)
思路
这个题首先要看懂grid数组是什么意思,比如Ex2,[[1, 2], [3, 4]],表示在(x,y)为坐标的(0,0)处放了一个方块,在(0,1)处放了两个,依此类推。 可能我这个放置方法和题目中的放置有些许不同,但是转换到三视图中,方块的个数是一样多的。再看看计算方法,x,y方向就是找最大值,把数组写成下边形式容易看出
[ [1, 2],
[3, 4]]
x,y方向就是行列分别找最大值,z方向是看数组的值,不为零,就加一。由于没有必要区分x,y轴,所以程序中就不必加以区分。
class Solution {
public:
int projectionArea(vector<vector<int>>& grid) {
int sum = 0;
for(int i = 0; i < grid.size(); i++)
{
int tmp1 = grid[i][0];
int tmp2 = grid[0][i];
for(int j = 0; j < grid.size(); j++)//每行每列找最大值
{
if(grid[i][j]>tmp1)
tmp1 = grid[i][j];
if(grid[j][i]>tmp2)
tmp2 = grid[j][i];
if(grid[i][j]!=0)//查看元素是否为零
sum++;
}
sum += (tmp1+tmp2);
}
return sum;
}
};