Find perimeter of shapes formed with 1 s in binary matrix | JavaScript program to find perimeter of area coverede 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
let R = 3 ; let C = 5 ; function numofneighbour ( mat , i , j ) { let count = 0 ; if ( i > 0 && mat [ i - 1 ] [ j ] == 1 ) count ++ ; if ( j > 0 && mat [ i ] [ j - 1 ] == 1 ) count ++ ; if ( i < R - 1 && mat [ i + 1 ] [ j ] == 1 ) count ++ ; if ( j < C - 1 && mat [ i ] [ j + 1 ] == 1 ) count ++ ; return count ; } function findperimeter ( mat ) { let perimeter = 0 ; for ( let i = 0 ; i < R ; i ++ ) for ( let j = 0 ; j < C ; j ++ ) if ( mat [ i ] [ j ] == 1 ) perimeter += ( 4 - numofneighbour ( mat , i , j ) ) ; return perimeter ; } let mat = [ [ 0 , 1 , 0 , 0 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 ] ] ; document . write ( findperimeter ( mat ) ) ;