LeetCode題解(0210):課程表II(Python)

長行發表於2021-01-04

題目:原題連結(中等)

標籤:圖、拓撲排序、廣度優先搜尋、深度優先搜尋

解法時間複雜度空間複雜度執行用時
Ans 1 (Python) O ( N ) O(N) O(N) O ( N ) O(N) O(N)84ms (12.88%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

def build_graph(edges):
    graph_in = collections.defaultdict(set)
    graph_out = collections.defaultdict(set)
    for edge in edges:
        graph_in[edge[1]].add(edge[0])
        graph_out[edge[0]].add(edge[1])
    return graph_out, graph_in


def topo(graph_in, graph_out):
    count = {}  # 節點入射邊統計
    queue = []  # 當前入射邊為0的節點列表

    # 統計所有節點的入射邊
    for node in graph_in:
        count[node] = len(graph_in[node])
    for node in graph_out:
        if node not in count:
            count[node] = 0
            queue.append(node)

    # 拓撲排序
    order = []
    while queue:
        node = queue.pop()
        order.append(node)
        for next in graph_out[node]:
            count[next] -= 1
            if count[next] == 0:
                queue.append(next)

    return order


class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        # 生成有向圖中邊的鄰接列表結構
        graph_in, graph_out = build_graph(prerequisites)

        # 拓撲排序
        order = topo(graph_in, graph_out)
        order_set = set(order)

        for node in graph_in:
            if node not in order:
                return []

        for i in range(numCourses):
            if i not in order_set:
                order.append(i)

        return order

相關文章