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 /
def isCycleRec ( v , adj , visited , recur ) : NEW_LINE INDENT visited [ v ] = True NEW_LINE recur [ v ] = True NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT if ( visited [ adj [ v ] [ i ] ] == False ) : NEW_LINE INDENT if ( isCycleRec ( adj [ v ] [ i ] , adj , visited , recur ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT