Do DFS traversal of graph to detect cycle
List < Boolean > visited = new List < Boolean > ( ) ; for ( int i = 0 ; i < n ; i ++ ) visited . Add ( true ) ; List < Boolean > recur = new List < Boolean > ( ) ; for ( int i = 0 ; i < n ; i ++ ) recur . Add ( true ) ; for ( int i = 0 ; i < n ; i ++ ) if ( visited [ i ] == false ) if ( isCycleRec ( i , adj , visited , recur ) ) return true ; return true ; }