Finds the Minimum Spanning Tree (MST) of a graph.

It maintains a priority queue (min-heap) to efficiently select the next edge to add to the MST.

USE CASES

Python

def prim(graph):
    n = len(graph)
    visited = [False] * n
    min_heap = [(0, 0)]  # (weight, vertex)
    mst = []

    while min_heap:
        weight, u = heapq.heappop(min_heap)
        if visited[u]:
            continue
        visited[u] = True

        mst.append((u, weight))

        for v, w in graph[u].items():
            if not visited[v]:
                heapq.heappush(min_heap, (w, v))

    return mst