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.
For example:
grid = [[1,2],[3,4]]
should return 34
grid = [[1,1,1],[1,0,1],[1,1,1]]
should return 32
grid = [[2,2,2],[2,1,2],[2,2,2]]
should return 46
Can you write a function to solve this problem efficiently?
def surfaceArea(grid):
n = len(grid)
area = 0
for i in range(n):
for j in range(n):
if grid[i][j] > 0:
area += 2 # Top and bottom surfaces
area += grid[i][j] * 4 # Initial side surfaces
# Subtract overlapping surfaces
if i > 0:
area -= min(grid[i][j], grid[i - 1][j])
if i < n - 1:
area -= min(grid[i][j], grid[i + 1][j])
if j > 0:
area -= min(grid[i][j], grid[i][j - 1])
if j < n - 1:
area -= min(grid[i][j], grid[i][j + 1])
return area
# Example usage
grid1 = [[1, 2], [3, 4]]
print(surfaceArea(grid1)) # Output: 34
grid2 = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
print(surfaceArea(grid2)) # Output: 32
grid3 = [[2, 2, 2], [2, 1, 2], [2, 2, 2]]
print(surfaceArea(grid3)) # Output: 46
(i, j)
with a tower of height v = grid[i][j]
, add 2 to the area (top and bottom surfaces).4 * v
to the area for the initial side surfaces.The code iterates through each cell of the n x n
grid once. For each cell, it performs a constant number of operations (additions, subtractions, and comparisons). Therefore, the time complexity is O(n^2), where n is the size of the grid.
The code uses a constant amount of extra space, regardless of the size of the input grid. It only uses a few variables to keep track of the area and loop indices. Therefore, the space complexity is O(1).
n = 0
), the code will still work correctly, returning a surface area of 0, because the loops will not execute.grid[i][j] = 0
), it does not contribute to the surface area, and the code correctly skips adding any area for that cell.