Find perimeter of shapes formed with 1 s in binary matrix | Python3 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
R = 3 NEW_LINE C = 5 NEW_LINE def numofneighbour ( mat , i , j ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( i > 0 and mat [ i - 1 ] [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( j > 0 and mat [ i ] [ j - 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( i < R - 1 and mat [ i + 1 ] [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( j < C - 1 and mat [ i ] [ j + 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def findperimeter ( mat ) : NEW_LINE INDENT perimeter = 0 ; NEW_LINE for i in range ( 0 , R ) : NEW_LINE INDENT for j in range ( 0 , C ) : NEW_LINE INDENT if ( mat [ i ] [ j ] ) : NEW_LINE INDENT perimeter += ( 4 - numofneighbour ( mat , i , j ) ) ; NEW_LINE DEDENT DEDENT DEDENT return perimeter ; NEW_LINE DEDENT mat = [ [ 0 , 1 , 0 , 0 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 ] ] NEW_LINE print ( findperimeter ( mat ) , end = " " ) ; NEW_LINE