题解 | 【模板】拓扑排序
import sys n, m = map(int, input().split(' ')) indegree = [0 for i in range(n + 1)] vis = [0 for i in range(n + 1)] indegree[0] = 100 edg = [[]for i in range(n + 1)] for zzz in range(m): x, y = map(int, input().split(' ')) indegree[y] += 1 edg[x].append(y) nodes = [] res = [] for i in range(n + 1): if indegree[i] == 0: nodes.append(i) while nodes: t = nodes.pop() vis[t] = 1 res.append(str(t)) for v in edg[t]: indegree[v] -= 1 if indegree[v] == 0: nodes.append(v) if sum(vis) < n: print(-1) else: print(' '.join(res))
没什么好说的,模板题,注意n=0还有要遍历到for i in range(n+1),这两个点坑了我