You are given an n x ngrid where you have placed some 1 x 1 x 1 cubes.
Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).
After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.
Return the total surface area of the resulting shapes.
Note: The bottom face of each shape counts toward its surface area.
Each cube has 6 faces, but adjacent cubes share faces. For each cell, we subtract shared faces with the cell above and to the left. The total is the sum for all cells.
For each cell, if it contains cubes, it contributes 6 faces per cube, but each shared face with an adjacent cube (up, down, left, right) removes 2 faces from the total. We sum the contributions for all cells.
classSolution {
public:int surfaceArea(vector<vector<int>>& grid) {
int n = grid.size(), ans =0;
for (int i =0; i < n; ++i) {
for (int j =0; j < n; ++j) {
if (grid[i][j] >0) {
ans += grid[i][j] *6- (grid[i][j] -1) *2;
if (i >0) ans -= min(grid[i][j], grid[i-1][j]) *2;
if (j >0) ans -= min(grid[i][j], grid[i][j-1]) *2;
}
}
}
return ans;
}
};
classSolution {
publicintsurfaceArea(int[][] grid) {
int n = grid.length, ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j]> 0) {
ans += grid[i][j]* 6 - (grid[i][j]- 1) * 2;
if (i > 0) ans -= Math.min(grid[i][j], grid[i-1][j]) * 2;
if (j > 0) ans -= Math.min(grid[i][j], grid[i][j-1]) * 2;
}
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funsurfaceArea(grid: Array<IntArray>): Int {
val n = grid.size
var ans = 0for (i in0 until n) {
for (j in0 until n) {
if (grid[i][j] > 0) {
ans += grid[i][j] * 6 - (grid[i][j] - 1) * 2if (i > 0) ans -= minOf(grid[i][j], grid[i-1][j]) * 2if (j > 0) ans -= minOf(grid[i][j], grid[i][j-1]) * 2 }
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsurfaceArea(self, grid: list[list[int]]) -> int:
n = len(grid)
ans =0for i in range(n):
for j in range(n):
if grid[i][j] >0:
ans += grid[i][j] *6- (grid[i][j] -1) *2if i >0:
ans -= min(grid[i][j], grid[i-1][j]) *2if j >0:
ans -= min(grid[i][j], grid[i][j-1]) *2return ans
impl Solution {
pubfnsurface_area(grid: Vec<Vec<i32>>) -> i32 {
let n = grid.len();
letmut ans =0;
for i in0..n {
for j in0..n {
if grid[i][j] >0 {
ans += grid[i][j] *6- (grid[i][j] -1) *2;
if i >0 {
ans -= grid[i][j].min(grid[i-1][j]) *2;
}
if j >0 {
ans -= grid[i][j].min(grid[i][j-1]) *2;
}
}
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
functionsurfaceArea(grid: number[][]):number {
constn=grid.length;
letans=0;
for (leti=0; i<n; ++i) {
for (letj=0; j<n; ++j) {
if (grid[i][j] >0) {
ans+=grid[i][j] *6- (grid[i][j] -1) *2;
if (i>0) ans-= Math.min(grid[i][j], grid[i-1][j]) *2;
if (j>0) ans-= Math.min(grid[i][j], grid[i][j-1]) *2;
}
}
}
returnans;
}