from collections import defaultdict
classSolution:deffindOrder(self, numCourses:int, prerequisites: List[List[int]])-> List[int]: adj = defaultdict(list)# { : []}for u, v in prerequisites: adj[v].append(u) marked =set() stack =set() has_cycle =False output =[]defdfs(v):nonlocal has_cycle
marked.add(v) stack.add(v)for w in adj[v]:if has_cycle:returnif w in stack: has_cycle =Trueelif w notin marked: dfs(w) stack.remove(v) output.append(v)for i inrange(numCourses):if i notin marked: dfs(i)return[]if has_cycle else output[::-1]
Note: could remove the reversal of the list and make adj list u→v instead but just did it this way to keep consistent with what I learned in 2C03 @ McMaster