from collections import defaultdict
class Solution:
    def findOrder(self, numCourses, prerequisites):
        graph = defaultdict(set)
        visit = [0 for _ in range(numCourses)]
        for x, y in prerequisites:
            graph[x].add(y)
        def dfs(i, path):
            if visit[i] == -1:
                return False
            if visit[i] == 1:
                return True
            visit[i] = -1
            for j in graph[i]:
                flag = dfs(j, path)
                if not flag:
                    return False
                else:
                    if visit[j] != 1:
                        path.append(j)
                        visit[j] = 1
            return True
        path = []
        for i in range(numCourses):
            flag = dfs(i, path)
            if not flag:
                return []
            else:
                if visit[i] != 1:
                    path.append(i)
                    visit[i] = 1
        if len(path) != numCourses:
            return []
        return path