Size of all connected non | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int BFS ( vector < vector < int > > & mat , int row , int col ) { int area = 0 ; queue < pair < int , int > > Q ; Q . push ( { row , col } ) ; while ( ! Q . empty ( ) ) { auto it = Q . front ( ) ; Q . pop ( ) ; 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 . push ( { r + 1 , c } ) ; Q . push ( { r - 1 , c } ) ; Q . push ( { r , c + 1 } ) ; Q . push ( { r , c - 1 } ) ; } return area ; } void sizeOfConnections ( vector < vector < int > > mat ) { vector < int > result ; 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 . push_back ( area ) ; } } } for ( int val : result ) cout << val << " ▁ " ; } int main ( ) { vector < vector < 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 ) ; return 0 ; }