Find the Surface area of a 3D figure in Python


Suppose we have a N*M matrix A, this is the representation of 3D figure. The height of the building at point (i, j) is A[i][j]. We have to find the surface area of the figure.

So, if the input is like N = 3, M = 3, A = [[1, 4, 5],[3, 3, 4],[1, 3, 5]], then the output will be 72.

To solve this, we will follow these steps −

  • res := 0

  • for i in range 0 to N, do

    • for j in range 0 to M, do

      • up_side := 0

      • left_side := 0

      • if i > 0, then

        • up_side := array[i - 1, j]

      • if j > 0, then

        • left_side := array[i, j - 1]

      • res := res + |array[i][j] - up_side| + |array[i][j] - left_side|

      • if i is same as N - 1, then

        • res := res + array[i, j]

      • if j is same as M - 1, then

        • res := res + array[i, j]

  • res := res + N * M * 2

  • return res

Example

Let us see the following implementation to get better understanding −

 Live Demo

M = 3
N = 3
def get_surface_area(array):
   res = 0
   for i in range(N):
      for j in range(M):
         up_side = 0
         left_side = 0
         if (i > 0):
            up_side = array[i - 1][j]
         if (j > 0):
            left_side = array[i][j - 1]
         res += abs(array[i][j] - up_side)+abs(array[i][j] - left_side)
         if (i == N - 1):
            res += array[i][j]
         if (j == M - 1):
            res += array[i][j]
   res += N * M * 2
   return res
array = [[1, 4, 5],[3, 3, 4],[1, 3, 5]]
print(get_surface_area(array))

Input

[[1, 4, 5],[3, 3, 4],[1, 3, 5]]

Output

72

Updated on: 27-Aug-2020

669 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements