수강신청을 할 때는 선이수 과목을 모두 이수했는지 확인하는 것이 중요해요!
위상 정렬에서도 선행 조건을 지키며 작업의 순서를 결정하게 됩니다.
1 -> 2 -> 5 -> 3 -> 6 -> 4 -> 7
from collections import deque
N = 7 # 노드의 수
# 연결 리스트: 각 노드에 연결된 간선 정보
graph = [
[],
[2, 5],
[3, 6],
[4],
[7],
[6],
[4],
[]
]
# 각 노드의 진입 차수 계산
indegree = [0] * (N + 1)
for i in range(1, N + 1):
for j in graph[i]:
indegree[j] += 1
indegree
리스트로 관리# 위상 정렬
def top_sort():
result = [] # 정렬 결과
queue = deque()
# 진입차수가 0인 노드 삽입
for i in range(1, N + 1):
if indegree[i] == 0:
queue.append(i)
# 큐가 빌 때까지
while queue:
# 노드를 꺼내고
curr = queue.popleft()
result.append(curr)
# 노드에서 꺼내는 간선을 제거
for i in graph[curr]:
indegree[i] -= 1
# 진입차수가 0이 된 경우 삽입
if indegree[i] == 0:
queue.append(i)
# 결과 출력
for i in result:
print(i, end=" ")
top_sort() # 1 2 5 3 6 4 7
indegree
리스트의 값만 1 감소시켜주면 됨from collections import deque
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
graph = [[] for _ in range(N + 1)]
indegree = [0] * (N + 1)
for _ in range(M):
# 학생 A가 학생 B 앞에 서야 됨
# 즉, 노드 A -> 노드 B 방향의 간선이 존재함
a, b = map(int, input().split())
graph[a].append(b)
indegree[b] += 1
def topsort():
queue = deque()
for i in range(1, N + 1):
if indegree[i] == 0:
queue.append(i)
while queue:
curr = queue.popleft()
print(curr, end=" ")
for i in graph[curr]:
indegree[i] -= 1
if indegree[i] == 0:
queue.append(i)
topsort()
전 아직 시작도 못 했는데 덕분에 보고 갑니다~