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