# leetcode-892. 三维形体的表面积

输入：[[2]]



输入：[[1,2],[3,4]]



输入：[[1,0],[0,2]]



输入：[[1,1,1],[1,0,1],[1,1,1]]



输入：[[2,2,2],[2,1,2],[2,2,2]]



1 <= N <= 50
0 <= grid[i][j] <= 50


## 解法一：根据题意

**思路：**根据其周围情况减去遮挡的表面积

class Solution {
public int surfaceArea(int[][] grid) {
if(grid==null||grid.length==0) return 0;
int res = 0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
int tmp = grid[i][j];
if(tmp==0) continue;
int sum = grid[i][j]*4+2;//总表面积
//上
if(i>0){
if(grid[i-1][j]<tmp){
sum -= grid[i-1][j];
}else{
sum -= tmp;
}
}
//下
if(i<grid.length-1){
if(grid[i+1][j]<tmp){
sum -= grid[i+1][j];
}else{
sum -= tmp;
}
}
//左
if(j>0){
if(grid[i][j-1]<tmp){
sum -= grid[i][j-1];
}else{
sum -= tmp;
}
}
//右
if(j<grid[i].length-1){
if(grid[i][j+1]<tmp){
sum -= grid[i][j+1];
}else{
sum -= tmp;
}
}
res += sum;
}
}
return res;
}
}


class Solution {
public int surfaceArea(int[][] grid) {
if(grid==null||grid.length==0) return 0;
int res = 0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
int tmp = grid[i][j];
if(tmp==0) continue;
int sum = grid[i][j]*4+2;//总表面积
if(i>0){
sum -= Math.min(grid[i-1][j],tmp);
}
if(i<grid.length-1){
sum -= Math.min(grid[i+1][j],tmp);
}
if(j>0){
sum -= Math.min(grid[i][j-1],tmp);
}
if(j<grid[i].length-1){
sum -= Math.min(grid[i][j+1],tmp);
}
res += sum;
}
}
return res;
}
}


## 解法二：利用加法

class Solution {
public int surfaceArea(int[][] grid) {
int[] dr = new int[]{0, 1, 0, -1};
int[] dc = new int[]{1, 0, -1, 0};

int N = grid.length;
int ans = 0;

for (int r = 0; r < N; ++r)
for (int c = 0; c < N; ++c)
if (grid[r][c] > 0) {
ans += 2;
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k];
int nc = c + dc[k];
int nv = 0;
if (0 <= nr && nr < N && 0 <= nc && nc < N)
nv = grid[nr][nc];

ans += Math.max(grid[r][c] - nv, 0);
}
}

return ans;
}
}



©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客