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 boolean isCycleRec ( int v , Vector < Integer > [ ] adj , Vector < Boolean > visited , Vector < Boolean > recur ) { visited . set ( v , true ) ; recur . set ( v , true ) ; for ( int i = 0 ; i < adj [ v ] . size ( ) ; i ++ ) { if ( visited . elementAt ( adj [ v ] . elementAt ( i ) ) == false ) { if ( isCycleRec ( adj [ v ] . elementAt ( i ) , adj , visited , recur ) ) return true ; }