Problem Description
Given an n x n grid where grid[i][j] represents a tower of 1 x 1 x 1 cubes stacked on the cell (i, j), compute the total surface area of the resulting 3D shapes after gluing together adjacent cubes. Note that the bottom of each shape contributes to the surface area.
Key Insights
- Each non-zero cell contributes top and bottom surfaces (2 faces).
- For every side (up, down, left, right), the contribution is the difference between the current cell's height and its neighbor's height, only if the current cell is taller.
- If a neighbor doesn't exist (i.e., the cell is at the boundary), treat neighbor height as 0.
- Iterate over all cells and sum up contributions from top, bottom, and all four sides.
Space and Time Complexity
Time Complexity: O(n²) since we traverse each cell once. Space Complexity: O(1) extra space (not counting input storage).
Solution
The approach involves iterating through the entire grid. For each cell, if its value is v > 0, add 2 to the surface area accounting for the top and bottom surfaces. Then, for each of the four sides (up, down, left, and right), compare the current cell's height v with the adjacent cell's height (or 0 for boundaries). The contribution from that side is max(v - neighbor, 0). This allows us to correctly account for overlapped surfaces when cubes are adjacent. The overall total is the sum of contributions from each cell across the grid.