演算法-圖論-拓撲排序

Frank23發表於2024-11-03

1. 拓撲排序(卡碼網 117)

from collections import deque, defaultdict

def main():
    num_node, num_edge = map(int, input().split())
    inDegrees = [0 for _ in range(num_node)]
    edges = defaultdict(list)
    for _ in range(num_edge):
        source, target = map(int, input().split())
        inDegrees[target] += 1
        edges[source].append(target)
    
    # 將入度為0的頂點入度
    que = deque([i for i in range(num_node) if inDegrees[i] == 0])
    result = []
    
    while que:
        cur = que.popleft()
        result.append(cur)
        for t in edges[cur]:
            inDegrees[t] -= 1
            if inDegrees[t] == 0:
                que.append(t)
    
    if len(result) == num_node:
        print(" ".join(map(str, result)))
    else:
        print(-1)
    
    
if __name__ == "__main__":
    main()

相關文章