Find perimeter of shapes formed with 1 s in binary matrix | C # 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
public class GFG { public const int R = 3 ; public const int C = 5 ; public static int numofneighbour ( int [ ] [ ] mat , int i , int j ) { int 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 ; } public static int findperimeter ( int [ ] [ ] mat ) { int perimeter = 0 ; for ( int i = 0 ; i < R ; i ++ ) { for ( int j = 0 ; j < C ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { perimeter += ( 4 - numofneighbour ( mat , i , j ) ) ; } } } return perimeter ; } public static void Main ( string [ ] args ) { int [ ] [ ] mat = new int [ ] [ ] { new int [ ] { 0 , 1 , 0 , 0 , 0 } , new int [ ] { 1 , 1 , 1 , 0 , 0 } , new int [ ] { 1 , 0 , 0 , 0 , 0 } } ; Console . WriteLine ( findperimeter ( mat ) ) ; } }