Check all 8 neighbours and do a Union with neighbour 's set if neighbour is  also 1
if ( j + 1 < n && a [ j + 1 ] [ k ] == 1 ) dus -> Union ( j * ( m ) + k , ( j + 1 ) * ( m ) + k ) ; if ( j - 1 >= 0 && a [ j - 1 ] [ k ] == 1 ) dus -> Union ( j * ( m ) + k , ( j - 1 ) * ( m ) + k ) ; if ( k + 1 < m && a [ j ] [ k + 1 ] == 1 ) dus -> Union ( j * ( m ) + k , ( j ) * ( m ) + k + 1 ) ; if ( k - 1 >= 0 && a [ j ] [ k - 1 ] == 1 ) dus -> Union ( j * ( m ) + k , ( j ) * ( m ) + k - 1 ) ; if ( j + 1 < n && k + 1 < m && a [ j + 1 ] [ k + 1 ] == 1 ) dus -> Union ( j * ( m ) + k , ( j + 1 ) * ( m ) + k + 1 ) ; if ( j + 1 < n && k - 1 >= 0 && a [ j + 1 ] [ k - 1 ] == 1 ) dus -> Union ( j * m + k , ( j + 1 ) * ( m ) + k - 1 ) ; if ( j - 1 >= 0 && k + 1 < m && a [ j - 1 ] [ k + 1 ] == 1 ) dus -> Union ( j * m + k , ( j - 1 ) * m + k + 1 ) ; if ( j - 1 >= 0 && k - 1 >= 0 && a [ j - 1 ] [ k - 1 ] == 1 ) dus -> Union ( j * m + k , ( j - 1 ) * m + k - 1 ) ; } }