Size of all connected non | Javascript 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 ; 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 print size 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
class pair { constructor ( first , second ) { this . first = first ; this . second = second ; } } function BFS ( mat , row , col ) { var area = 0 ; var Q = [ ] ; Q . push ( new pair ( row , col ) ) ; while ( Q . length != 0 ) { var it = Q [ 0 ] ; Q . shift ( ) ; var r = it . first , c = it . second ; if ( r < 0 c < 0 r > 4 c > 4 ) continue ; if ( mat [ r ] [ c ] == 0 ) continue ; if ( mat [ r ] == 1 ) { mat [ r ] = 0 ; area ++ ; } Q . push ( new pair ( r + 1 , c ) ) ; Q . push ( new pair ( r - 1 , c ) ) ; Q . push ( new pair ( r , c + 1 ) ) ; Q . push ( new pair ( r , c - 1 ) ) ; } return area ; } function sizeOfConnections ( mat ) { var result = [ ] ; for ( var row = 0 ; row < 5 ; ++ row ) { for ( var col = 0 ; col < 5 ; ++ col ) { if ( mat [ row ] [ col ] == 1 ) { var area = BFS ( mat , row , col ) ; result . push ( area ) ; } } } for ( var val of result ) document . write ( val + " " ) ; } var 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 ] ] ; sizeOfConnections ( mat ) ;