A simple Graph DFS based recursive function to check if there is cycle in graph with vertex v as root of DFS . Refer below article for details . https : www . geeksforgeeks . org / detect - cycle - in - a - graph /
bool isCycleRec ( int v , vector < int > adj [ ] , vector < bool > & visited , vector < bool > & recur ) { visited [ v ] = true ; recur [ v ] = true ; for ( int i = 0 ; i < adj [ v ] . size ( ) ; i ++ ) { if ( visited [ adj [ v ] [ i ] ] == false ) { if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) return true ; }