enum { white, gray, black, }; bool is_cyclic_rec( int v, const int * const *neighs, char *vis ) { if ( vis[ v ] == black ) return false; if ( vis[ v ] == gray ) return true; vis[ v ] = gray; for( const int *succ = neighs[ v ]; *succ >= 0; ++ succ ) if ( is_cyclic_rec( *succ, neighs, vis ) ) return true; vis[ v ] = black; return false; } bool is_cyclic( const int * const *neighs, char *scratch ) { for ( int v = 0; neighs[ v ]; ++ v ) scratch[ v ] = white; for ( int v = 0; neighs[ v ]; ++ v ) { if ( is_cyclic_rec( v, neighs, scratch ) ) return true; } return false; }