Computer >> Computer tutorials >  >> Programming >> Python

Surface Area of 3D Shapes in Python


Suppose there is a N x N grid, we place some 1 x 1 x 1 cubes. in it. Now for each value v = grid[i][j] represents a tower of v cubes placed on top of grid cell(i, j). We have to find the total surface area of the resulting shapes.

So, if the input is like [[1,2],[3,4]], then the output will be 34.

To solve this, we will follow these steps −

  • Define a function adjacentArea(). This will take row
  • area := 0
  • for i in range 0 to size of row - 1, do
    • if row[i] and row[i + 1] is non-zero, then
      • area := area + 2 * minimum of row[i], row[i+1]
  • return area
  • From the main method do the following −
  • z := 2* (sum of (sum of value i in row) for all row in grid)
  • x_plus_y := sum of all elements in the grid * 4
  • x_adjacent := sum of adjacentArea(row) for all row in grid
  • y_adjacent := sum of adjacentArea(row) for all column in the grid
  • return z +(x_plus_y - x_adjacent - y_adjacent)

Let us see the following implementation to get better understanding −

Example

class Solution:
   def surfaceArea(self, grid):
      def adjacentArea(row):
         area = 0
         for i in range(len(row) - 1):
            if row[i] and row[i + 1]:
               area += 2 * min(row[i], row[i+1])
            return area
      z = sum([sum(i > 0 for i in row) for row in grid]) * 2
      x_plus_y = sum([sum(row) for row in grid]) * 4
      x_adjacent = sum([adjacentArea(row) for row in grid])
      y_adjacent = sum([adjacentArea(row) for row in zip(*grid)])
      return z + (x_plus_y - x_adjacent - y_adjacent)
ob = Solution()
print(ob.surfaceArea([[1,2],[3,4]]))

Input

[[1,2],[3,4]]

Output

34