A possible implementation of DFS in Python is outlined below: from collections import defaultdict def findOrder ( numCourses , prerequisites ) : graph = defaultdict ( list ) for u , v in prerequisites : graph [ v ] . append ( u ) visited = [ 0 for _ in range ( numCourses ) ] stack = [ ] for course in range ( numCourses ) : if not dfs ( course , graph , visited , stack ) : return [ - 1 ] return stack [ : : - 1 ] def dfs ( course , graph , visited , stack ) : if visited [ course ] == - 1 : return False if visited [ course ] == 1 : return True visited [ course ] = - 1 for pre in graph [ course ] : if not dfs ( pre , graph , visited , stack ) : return False visited [ course ] = 1 stack . append ( course ) return True In this implementation of DFS, a course is designated as -1 while the DFS is being conducted from that course, and it is labeled as 1 once the DFS from that course is complete. If we encounter a course marked as -1 at any point during the DFS, it indicates that a cycle exists in the graph, leading us to return False . Conversely, if no cycles are found, we mark the node as completely processed ( 1 ) and append it to our course schedule (stack).