Check loop in array according to given constraints | C # program to check if a given array is cyclic or not ; 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 / ; There is a cycle if an adjacent is visited and present in recursion call stack recur [ ] ; Returns true if [ ] arr has cycle ; Create a graph using given moves in [ ] arr ; Do DFS traversal of graph to detect cycle ; Driver Code
using System ; using System . Collections . Generic ; public class GFG { 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 ; } else if ( visited [ adj [ v ] [ i ] ] == true && recur [ adj [ v ] [ i ] ] == true ) return true ; } recur [ v ] = false ; return false ; } static bool isCycle ( int [ ] arr , int n ) { List < int > [ ] adj = new List < int > [ n ] ; for ( int i = 0 ; i < n ; i ++ ) if ( i != ( i + arr [ i ] + n ) % n && adj [ i ] != null ) adj [ i ] . Add ( ( i + arr [ i ] + n ) % n ) ; 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 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , - 1 , 1 , 2 , 2 } ; int n = arr . Length ; if ( isCycle ( arr , n ) == true ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }