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
< ? php $ M = 3 ; $ N = 3 ; function contribution_height ( $ current , $ previous ) { return abs ( $ current - $ previous ) ; } function surfaceArea ( $ A ) { global $ M ; global $ N ; $ ans = 0 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { for ( $ j = 0 ; $ j < $ M ; $ j ++ ) { $ up = 0 ; $ left = 0 ; if ( $ i > 0 ) $ up = $ A [ $ i - 1 ] [ $ j ] ; if ( $ j > 0 ) $ left = $ A [ $ i ] [ $ j - 1 ] ; $ ans += contribution_height ( $ A [ $ i ] [ $ j ] , $ up ) + contribution_height ( $ A [ $ i ] [ $ j ] , $ left ) ; if ( $ i == $ N - 1 ) $ ans += $ A [ $ i ] [ $ j ] ; if ( $ j == $ M - 1 ) $ ans += $ A [ $ i ] [ $ j ] ; } } $ ans += $ N * $ M * 2 ; return $ ans ; } $ A = array ( array ( 1 , 3 , 4 ) , array ( 2 , 2 , 3 ) , array ( 1 , 2 , 4 ) ) ; echo surfaceArea ( $ A ) ;