Size of all connected non | Python3 program to implement the above approach ; Function to find size of all the islands from the given matrix ; Initialize a queue for the BFS traversal ; Iterate until the queue is empty ; Top element of queue ; Pop the element Q . pop ( ) ; ; Check for boundaries ; Check if current element is 0 ; Check if current element is 1 ; Mark the cell visited ; Incrementing the size ; Traverse all neighbors ; Return the answer ; Function to prsize of each connections ; Stores the size of each connected non - empty ; Check if the cell is non - empty ; Function call ; Print the answer ; Driver Code
from collections import deque NEW_LINE def BFS ( mat , row , col ) : NEW_LINE INDENT area = 0 NEW_LINE Q = deque ( ) NEW_LINE Q . append ( [ row , col ] ) NEW_LINE while ( len ( Q ) > 0 ) : NEW_LINE INDENT it = Q . popleft ( ) NEW_LINE r , c = it [ 0 ] , it [ 1 ] NEW_LINE if ( r < 0 or c < 0 or r > 4 or c > 4 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( mat [ r ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( mat [ r ] == 1 ) : NEW_LINE INDENT mat [ r ] = 0 NEW_LINE area += 1 NEW_LINE DEDENT Q . append ( [ r + 1 , c ] ) NEW_LINE Q . append ( [ r - 1 , c ] ) NEW_LINE Q . append ( [ r , c + 1 ] ) NEW_LINE Q . append ( [ r , c - 1 ] ) NEW_LINE DEDENT return area NEW_LINE DEDENT def sizeOfConnections ( mat ) : NEW_LINE INDENT result = [ ] NEW_LINE for row in range ( 5 ) : NEW_LINE INDENT for col in range ( 5 ) : NEW_LINE INDENT if ( mat [ row ] [ col ] == 1 ) : NEW_LINE INDENT area = BFS ( mat , row , col ) ; NEW_LINE result . append ( area ) NEW_LINE DEDENT DEDENT DEDENT for val in result : NEW_LINE INDENT print ( val , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 1 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 1 , 1 ] , [ 1 , 0 , 0 , 1 , 1 ] , [ 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 1 , 1 , 1 ] ] NEW_LINE sizeOfConnections ( mat ) NEW_LINE DEDENT