题目:
On a
N * N
grid, we place some1 * 1 * 1
cubes.
Each valuev = grid[i][j]
represents a tower ofv
cubes placed on top of grid cell(i, j)
. Return the total surface area of the resulting shapes.
Example 1:Input: [[2]] Output: 10
Example 2:
Input: [[1,2],[3,4]] Output: 34
Example 3:
Input: [[1,0],[0,2]] Output: 16
Example 4:
Input: [[1,1,1],[1,0,1],[1,1,1]] Output: 32
Example 5:
Input: [[2,2,2],[2,1,2],[2,2,2]] Output: 46
Note:
1 <= N <= 50 0 <= grid[i][j] <= 50
解释:
求一个3D物体的表面积。
一般关于表面积的题目都是总的表面积减去某个值。
总面数减掉底边重合的(高度4+2,2表示上下两个底面,4表示一圈有四个表面),减掉侧边重合的(侧边重合的最小值2)。
python代码:
class Solution(object):
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
if not grid:
return 0
result=0
N=len(grid)
for i in range(N):
for j in range(N):
if grid[i][j]:
result+=grid[i][j]*4+2
if i:
result-=min(grid[i-1][j],grid[i][j])*2
if j:
result-=min(grid[i][j-1],grid[i][j])*2
return result
c++代码:
#include<algorithm>
using namespace std;
class Solution {
public:
int surfaceArea(vector<vector<int>>& grid) {
int N=grid.size();
int result=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
if(grid[i][j])
{ //这个结果是不减去侧面重合的
result+=grid[i][j]*4+2;
}
//遍历到一个立方体就检测它是否与其左边的和下边的(俯视图)立方体重叠。若是重叠就减去*2
if (i)
//重叠的时候去掉两个面
result-=min(grid[i-1][j],grid[i][j])*2;
if(j)
result-=min(grid[i][j-1],grid[i][j])*2;
}
}
return result;
}
};
总结:
要有充分的空间想象能力,嗯。