human
Give me a code to check loop in array according to given constraints and the other steps required given the following:
Check loop in array according to given constraints | 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"
How can the above be solved in Python?
assistant
#Here is code to check loop in array according to given constraints and the other steps required.
 def isCycleRec ( v , adj , visited , recur ) :
	visited [ v ] = True
	recur [ v ] = True
	for i in range ( len ( adj [ v ] ) ) :
		if ( visited [ adj [ v ] [ i ] ] == False ) :
			if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) :
				return True
		elif ( visited [ adj [ v ] [ i ] ] == True and recur [ adj [ v ] [ i ] ] == True ) :
			return True
	recur [ v ] = False
	return False
def isCycle ( arr , n ) :
	adj = [ [ ] for i in range ( n ) ]
	for i in range ( n ) :
		if ( i != ( i + arr [ i ] + n ) % n ) :
			adj [ i ] . append ( ( i + arr [ i ] + n ) % n )
	visited = [ False ] * n
	recur = [ False ] * n
	for i in range ( n ) :
		if ( visited [ i ] == False ) :
			if ( isCycleRec ( i , adj , visited , recur ) ) :
				return True
	return True
if __name__ == ' _ _ main _ _ ' :
	arr = [ 2 , - 1 , 1 , 2 , 2 ]
	n = len ( arr )
	if ( isCycle ( arr , n ) ) :
		print ( " Yes " )
	else :
		print ( " No " )