Try all N adjacent of ( * x , * y ) starting from a random adjacent . Find the adjacent with minimum degree .
int start = rand ( ) % N ; for ( int count = 0 ; count < N ; ++ count ) { int i = ( start + count ) % N ; nx = * x + cx [ i ] ; ny = * y + cy [ i ] ; if ( ( isempty ( a , nx , ny ) ) & & ( c = getDegree ( a , nx , ny ) ) < min_deg ) { min_deg_idx = i ; min_deg = c ; } }