Surface Area of 3D Shapes
Problem
You are given an n x n
grid
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.
Constraints
n == grid.length == grid[i].length
1 <= n <= 50
0 <= grid[i][j] <= 50
Solution
The problem Surface Area of 3D Shapes
can be solved by calculating maximum possible surface for each cell and subtracting surfaces that are glued with adjacent cubes.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
int surfaceArea(vector<vector<int>> &grid)
{
int ret = 0;
int len = grid.size();
for (int i = 0; i < len; i++)
for (int j = 0; j < len; j++)
{
if (grid[i][j])
ret += 2 + 4 * grid[i][j];
if (i > 0)
ret -= min(grid[i][j], grid[i - 1][j]);
if (j > 0)
ret -= min(grid[i][j], grid[i][j - 1]);
if (i < len - 1)
ret -= min(grid[i][j], grid[i + 1][j]);
if (j < len - 1)
ret -= min(grid[i][j], grid[i][j + 1]);
}
return ret;
}
};