classSolution: defcanFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: node = [[] for _ inrange(numCourses)] for p in prerequisites: node[p[0]].append(p[1]) visited = set() defdfs(index, cycle): if index in cycle: # cycle detected returnFalse if index in visited: # visited before, so doesn't need dfs any more returnTrue # put this course in dfs path current_cycle = cycle + [index] for i in node[index]: ifnot dfs(i, current_cycle): returnFalse # dfs is done and all course is ok! visited.add(index) returnTrue for i inrange(numCourses): ifnot dfs(i, []): returnFalse returnTrue