题目地址:
https://leetcode.com/problems/surface-area-of-3d-shapes/
给定一个非负整数的 n × n n\times n n×n的二维数组 A A A, A [ i ] [ j ] A[i][j] A[i][j]代表 ( i , j ) (i,j) (i,j)这个位置的高度,想象一下将这些方块都粘合在一起,求粘合起来之后的物体表面积。
考虑 A [ i ] [ j ] A[i][j] A[i][j]贡献的表面积,如果 A [ i ] [ j ] = 0 A[i][j]=0 A[i][j]=0,那么其不贡献表面积;否则其上下方贡献表面积为 2 2 2,其余四个方向贡献的面积取决于其高度减去其四个邻居的高度(如果不高于邻居则不贡献表面积,否则贡献差值)。代码如下:
public class Solution {
public int surfaceArea(int[][] grid) {
int n = grid.length, res = 0;
int[] d = {-1, 0, 1, 0, -1};
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
res += calc(i, j, grid, d);
}
}
return res;
}
int calc(int x, int y, int[][] g, int[] d) {
if (g[x][y] == 0) {
return 0;
}
int cnt = 0;
for (int i = 0; i < 4; i++) {
int nx = x + d[i], ny = y + d[i + 1];
if (0 <= nx && nx < g.length && 0 <= ny && ny < g.length) {
cnt += Math.max(0, g[x][y] - g[nx][ny]);
} else {
cnt += g[x][y];
}
}
return cnt + 2;
}
}
时间复杂度 O ( n 2 ) O(n^2) O(n2),空间 O ( 1 ) O(1) O(1)。