Surface Area of 3D Shapes
Here’s a way to calculate the total surface area of the resulting 3D shapes formed by the cubes placed on the grid.
|
|
Here’s how this code works:
- We iterate through each cell
(i, j)
of the grid. - For each cell, if it contains cubes (
grid[i][j] > 0
), we add 2 to the surface area for the top and bottom faces. - Then, we iterate through the four possible directions
(1, 0), (-1, 0), (0, 1), (0, -1)
to check the adjacent cells. We calculate the difference between the current cell’s cube count and the neighbor’s cube count to find the exposed surface area for that side. If the adjacent cell is out of bounds, we consider the neighbor’s cube count as 0. - We sum up all these contributions to get the total surface area for the grid.