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 /
static bool isCycleRec ( int v , List < int > [ ] adj , List < Boolean > visited , List < Boolean > recur ) { visited [ v ] = true ; recur [ v ] = true ; for ( int i = 0 ; i < adj [ v ] . Count ; i ++ ) { if ( visited [ adj [ v ] [ i ] ] == false ) { if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) return true ; }