题目:原题链接(中等)

标签:图、拓扑排序

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N + E ) O(N+E) O(N+E) O ( N + E ) O(N+E) O(N+E) 88ms (31.87%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def minimumSemesters(self, n: int, relations: List[List[int]]) -> int:
        graph_in = collections.defaultdict(set)
        graph_out = collections.defaultdict(set)
        for edge in relations:
            graph_in[edge[1]].add(edge[0])
            graph_out[edge[0]].add(edge[1])

        count = {}  # 节点入射边统计
        queue = collections.deque()  # 当前入射边为0的节点列表

        # 统计所有节点的入射边
        for node in graph_in:
            count[node] = len(graph_in[node])
        for i in range(1, n + 1):
            if i not in count:
                count[i] = 0
                queue.append(i)

        if len(queue) == 0:
            return -1

        # 拓扑排序
        ans = 0
        order = []
        while queue:
            for _ in range(len(queue)):
                node = queue.popleft()
                order.append(node)
                for next in graph_out[node]:
                    count[next] -= 1
                    if count[next] == 0:
                        queue.append(next)
            ans += 1

        if len(order) == n:
            return ans
        else:
            return -1