Prim 알고리즘
import heapq
n = 3
adj = [[],
[(1,2), (3,3)],
[(1,1), (2,3)],
[(2, 2), (3,1)]
]
# Prim 알고리즘
visited = [False] * (n+1)
queue = list()
queue.append((0, 1))
answer = 0
while queue:
cost, node = heapq.heappop(queue)
if visited[node]:
continue
visited[node] = True
answer += cost
for next_cost, next_node in adj[node]:
if not visited[next_node]:
heapq.heappush(queue, (next_cost, next_node))
# MST 가중치 출력
print(answer)
실행 결과로 3이 출력된다.
Kruskal 알고리즘
# Kruskal 알고리즘
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(x, y):
x_root = find(x)
y_root = find(y)
if x_root != y_root:
parent[y_root] = x_root
return True
return False
n = 3
parent = [i for i in range(n+1)]
edges = [(1, 1, 2), (2, 3, 2), (3, 1, 3)]
answer = 0
for c, a, b in edges:
if union(a, b):
answer += c
print(answer)
위와 마찬가지로 실행 결과로 3이 출력된다.
'CS > Python' 카테고리의 다른 글
| 파이썬으로 플로이드-워셜 알고리즘 구현하기 (0) | 2025.04.01 |
|---|---|
| 파이썬으로 DFS, BFS 구현하기 (0) | 2025.04.01 |
| 파이썬으로 다익스트라 알고리즘 구현하기 (0) | 2025.03.31 |
| 파이썬으로 트리 순회 구현하기 (0) | 2025.03.27 |
| 파이썬으로 이진 탐색 트리 구현하기 (0) | 2025.03.27 |