Find perimeter of shapes formed with 1 s in binary matrix | PHP program to find perimeter of area covered by 1 in 2D matrix consisits of 0 ' s ▁ and ▁ 1' s . ; Find the number of covered side for mat [ i ] [ j ] . ; UP ; LEFT ; DOWN ; RIGHT ; Returns sum of perimeter of shapes formed with 1 s ; Traversing the matrix and finding ones to calculate their contribution . ; Driver Code
< ? php $ R = 3 ; $ C = 5 ; function numofneighbour ( $ mat , $ i , $ j ) { global $ R ; global $ C ; $ count = 0 ; if ( $ i > 0 && ( $ mat [ $ i - 1 ] [ $ j ] ) ) $ count ++ ; if ( $ j > 0 && ( $ mat [ $ i ] [ $ j - 1 ] ) ) $ count ++ ; if ( ( $ i < $ R - 1 ) && ( $ mat [ $ i + 1 ] [ $ j ] ) ) $ count ++ ; if ( ( $ j < $ C - 1 ) && ( $ mat [ $ i ] [ $ j + 1 ] ) ) $ count ++ ; return $ count ; } function findperimeter ( $ mat ) { global $ R ; global $ C ; $ perimeter = 0 ; for ( $ i = 0 ; $ i < $ R ; $ i ++ ) for ( $ j = 0 ; $ j < $ C ; $ j ++ ) if ( $ mat [ $ i ] [ $ j ] ) $ perimeter += ( 4 - numofneighbour ( $ mat , $ i , $ j ) ) ; return $ perimeter ; } $ mat = array ( array ( 0 , 1 , 0 , 0 , 0 ) , array ( 1 , 1 , 1 , 0 , 0 ) , array ( 1 , 0 , 0 , 0 , 0 ) ) ; echo findperimeter ( $ mat ) , " STRNEWLINE " ; ? >