Find the Surface area of a 3D figure | Declaring the size of the matrix ; Absolute Difference between the height of two consecutive blocks ; Function To calculate the Total surfaceArea . ; Traversing the matrix . ; If we are traveling the topmost row in the matrix , we declare the wall above it as 0 as there is no wall above it . ; If we are traveling the leftmost column in the matrix , we declare the wall left to it as 0 as there is no wall left it . ; If its not the topmost row ; If its not the leftmost column ; Summing up the contribution of by the current block ; If its the rightmost block of the matrix it will contribute area equal to its height as a wall on the right of the figure ; If its the lowest block of the matrix it will contribute area equal to its height as a wall on the bottom of the figure ; Adding the contribution by the base and top of the figure ; Driver Code
M = 3 ; NEW_LINE N = 3 ; NEW_LINE def contribution_height ( current , previous ) : NEW_LINE INDENT return abs ( current - previous ) ; NEW_LINE DEDENT def surfaceArea ( A ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT up = 0 ; NEW_LINE left = 0 ; NEW_LINE if ( i > 0 ) : NEW_LINE INDENT up = A [ i - 1 ] [ j ] ; NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT left = A [ i ] [ j - 1 ] ; NEW_LINE DEDENT ans += contribution_height ( A [ i ] [ j ] , up ) + contribution_height ( A [ i ] [ j ] , left ) ; NEW_LINE if ( i == N - 1 ) : NEW_LINE INDENT ans += A [ i ] [ j ] ; NEW_LINE DEDENT if ( j == M - 1 ) : NEW_LINE INDENT ans += A [ i ] [ j ] ; NEW_LINE DEDENT DEDENT DEDENT ans += N * M * 2 ; NEW_LINE return ans ; NEW_LINE DEDENT A = [ [ 1 , 3 , 4 ] , [ 2 , 2 , 3 ] , [ 1 , 2 , 4 ] ] ; NEW_LINE print ( surfaceArea ( A ) ) ; NEW_LINE