hello2jolee / algorithm_python

코딩테스트 대비
0 stars 0 forks source link

위상정렬(그래프) #27

Open hello2jolee opened 3 years ago

hello2jolee commented 3 years ago

위상정렬(그래프 정렬)

진입차수란?

hello2jolee commented 3 years ago
from collections import deque

def solution(N, M, array):
    # 데이터 저장용 그래프
    graph = [[0] * (N + 1) for _ in range(N + 1)]
    # 진입차수 계산용도
    degree = [0] * (N + 1)
    dQ = deque()

    for a, b in array:
        graph[a][b] = 1
        degree[b] += 1

    for i in range(1, N + 1):
        if degree[i] == 0:
            dQ.append(i)

    while dQ:
        x = dQ.popleft()
        print(x, end= ' ')
        for i in range(1, N + 1):
            if graph[x][i] == 1:
                degree[i] -= 1
                if degree[i] == 0:
                    dQ.append(i)