import heapq
def prim_mst(graph, start=0):
mst = []
visited = set([start])
edges = [(cost, start, to) for to, cost in graph[start]]
heapq.heapify(edges)
while edges:
cost, frm, to = heapq.heappop(edges)
if to not in visited:
visited.add(to)
mst.append((frm, to, cost))
for to_next, cost_next in graph[to]:
if to_next not in visited:
heapq.heappush(edges, (cost_next, to, to_next))
return mst
# Example graph as adjacency list: vertex -> list of (neighbor, cost)
graph = {
0: [(1, 2), (3, 6)],
1: [(0, 2), (2, 3), (3, 8), (4, 5)],
2: [(1, 3), (4, 7)],
3: [(0, 6), (1, 8), (4, 9)],
4: [(1, 5), (2, 7), (3, 9)]
}
mst = prim_mst(graph)
for edge in mst:
print(edge)