Size of all connected non | Java 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
import java . util . * ; import java . lang . * ; class GFG { static class pair { int first , second ; pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int BFS ( int [ ] [ ] mat , int row , int col ) { int area = 0 ; Queue < pair > Q = new LinkedList < > ( ) ; Q . add ( new pair ( row , col ) ) ; while ( ! Q . isEmpty ( ) ) { pair it = Q . peek ( ) ; Q . poll ( ) ; int r = it . first , c = it . second ; if ( r < 0 c < 0 r > 4 c > 4 ) continue ; if ( mat [ r ] == 0 ) continue ; if ( mat [ r ] == 1 ) { mat [ r ] = 0 ; area ++ ; } Q . add ( new pair ( r + 1 , c ) ) ; Q . add ( new pair ( r - 1 , c ) ) ; Q . add ( new pair ( r , c + 1 ) ) ; Q . add ( new pair ( r , c - 1 ) ) ; } return area ; } static void sizeOfConnections ( int [ ] [ ] mat ) { ArrayList < Integer > result = new ArrayList < > ( ) ; for ( int row = 0 ; row < 5 ; ++ row ) { for ( int col = 0 ; col < 5 ; ++ col ) { if ( mat [ row ] [ col ] == 1 ) { int area = BFS ( mat , row , col ) ; result . add ( area ) ; } } } for ( int val : result ) System . out . print ( val + " ▁ " ) ; } public static void main ( String [ ] args ) { int [ ] [ ] 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 ) ; } }