第四步判断是否含循环必不可少,要根据题目要求来处理。除非L310 min height明确一定有解,而L269外星人字典就明确可能无解
Python代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
deftopological_sort(self, graph: List[List[int]], n: int) -> List[int]: in_degree = [0] * n for i in range(len(graph)): for j in range(len(graph[i])): in_degree[graph[i][j]] += 1
start_nodes = [i for i in range(len(in_degree)) if in_degree[i] == 0] queue, res = deque(start_nodes), []
while queue: root = queue.popleft() res.append(root) for i in graph[root]: in_degree[i] -= 1 if in_degree[i] == 0: queue.append(i) return res if len(res) == n elseNone