# 题干

输入：[[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

# Java代码

package daily;

public class SurfaceArea {
public int surfaceArea(int[][] grid) {
int n=grid.length;
//正方体数量
int cubeNum=0;
//面数量
int face=0;
for (int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(grid[i][j]>0){
//记录正方体数量
cubeNum+=grid[i][j];
// 面数量
face+=grid[i][j]-1;
}
if(i>0){
//侧面数量 下同
face+=Math.min(grid[i][j],grid[i-1][j]);
}
if(j>0){
face+=Math.min(grid[i][j-1],grid[i][j]);
}

}
}
return  cubeNum*6-face*2;
}

public  static  void main(String [] args){
SurfaceArea surfaceArea= new SurfaceArea();
int [][]test={{1,1,1},{1,0,1},{1,1,1}};
int res=surfaceArea.surfaceArea(test);
System.out.println(res);

}
}


# leetcode上更快的直接相加法

class Solution {
public int surfaceArea(int[][] grid) {
int result = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
result += getFaceNum(grid, i, j);
}
}
return result;
}

private int getFaceNum(int[][] grid, int i, int j) {
if (grid[i][j] == 0){
return 0;
}
int faceNum = grid[i][j] * 4 + 2;
if (i - 1 >= 0) {
faceNum -= Math.min(grid[i][j], grid[i - 1][j]);
}
if (j - 1 >= 0) {
faceNum -= Math.min(grid[i][j], grid[i][j - 1]);
}
if (i + 1 < grid.length) {
faceNum -= Math.min(grid[i][j], grid[i + 1][j]);
}
if (j + 1 < grid[0].length) {
faceNum -= Math.min(grid[i][j], grid[i][j + 1]);
}
return faceNum;
}
}


©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试