题解 | #【模板】拓扑排序#
【模板】拓扑排序
https://www.nowcoder.com/practice/88f7e156ca7d43a1a535f619cd3f495c
from collections import deque n, m = map(int, input().split()) # 读取顶点数和边数 graph = {v: set() for v in range(1, n + 1)} # 邻接表来描述图(键:顶点,值:相邻点集合) indegree = {v: 0 for v in range(1, n + 1)} # 记录每个顶点的入度(键:顶点,值:入度) result = [] # 存放拓扑序列 # 读取输入并构建邻接表以及入度字典 for _ in range(m): u, v = map(int, input().split()) graph[u].add(v) indegree[v] += 1 # 使用队列来进行拓扑排序 queue = deque() for v, degree in indegree.items(): if degree == 0: # 把入度为0的顶点加入队列方便进行相关操作 queue.append(v) while queue: # 开始处理入度为0的顶点 u = queue.popleft() # 时间复杂度O(1) result.append(u) # 先把顶点加入结果集 for v in graph[u]: indegree[v] -= 1 # 相邻顶点入度减1(删除边) if indegree[v] == 0: # 若删除边之后相邻顶点的入度也为0,加入结果集 queue.append(v) # 判断是否为有效拓扑序列 if len(result) != n: print(-1) else: print(" ".join(map(str, result)))