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.
Example 1:
Input: grid = [[1,2],[3,4]] Output: 34
Example 2:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 32
Example 3:
Input: grid = [[2,2,2],[2,1,2],[2,2,2]] Output: 46
Constraints:
n == grid.length == grid[i].length1 <= n <= 500 <= grid[i][j] <= 50This approach involves calculating the total surface area by starting from the maximum theoretical surface area (each cube contributing six sides) and subtracting the overlapping sides between adjacent cubes.
This C solution iterates through each cell in the grid. For each cube, it accounts for all six sides and subtracts the shared face between adjacent cubes. The use of fmin ensures we only subtract surface area up to the height of the shorter stack.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2), where n is the dimension of the grid.
Space Complexity: O(1), as no additional space proportional to the input size is used.
This approach focuses on iterating through the grid and calculating surface additions by examining each pair of adjacent cells directly.
This C solution calculates the surface area while accounting for shared walls between directly adjacent stacks of cubes. It inherently ensures overlap is addressed during iteration.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n^2).
Space Complexity: O(1).
| Approach | Complexity |
|---|---|
| Direct Calculation of Surface Area | Time Complexity: O(n^2), where n is the dimension of the grid. Space Complexity: O(1), as no additional space proportional to the input size is used. |
| Iterative Side-by-Side Calculation | Time Complexity: O(n^2). Space Complexity: O(1). |
Surface Area and Volume Review (Geometry) • Mario's Math Tutoring • 262,625 views views
Watch 9 more video solutions →Practice Surface Area of 3D Shapes with our built-in code editor and test cases.
Practice on FleetCode