DFS를 활용하는 방법
from collections import deque
N = 1000
s = deque()
g = [[0 for _ in range(N+1)] for _ in range(N+1)]
visited = [False for _ in range(N+1)]
def dfs(v):
visited[v] = True
for i in range(len(g[v])):
if not visited[g[v][i]]:
dfs(i)
s.append(v)
BFS와 in-degree(진입차수) 활용
import heapq,sys
input = lambda: sys.stdin.readline().rstrip()
N,M = map(int,input().split())
g = [[] for _ in range(N+1)]
indegree = [0 for _ in range(N+1)]
pq = [] # mean heap
for i in range(M):
s,e = map(int,input().split())
g[s].append(e)
indegree[e] += 1
for i in range(1,N+1):
if indegree[i] == 0:
heapq.heappush(pq,i)
while pq:
poped = heapq.heappop(pq)
print(poped,end = ' ')
for i in g[poped]:
indegree[i] -= 1
if indegree[i] == 0:
heapq.heappush(pq,i)