Prim's Algorithm

Graph Selection

Playback Controls

Select a graph to begin MST visualization

Prim's Info

Key Features:

  • • Finds Minimum Spanning Tree
  • • Uses vertex-based approach
  • • Time complexity: O((V+E) log V)
  • • Uses priority queue
  • • Grows tree from single vertex

Legend:

Current Vertex
MST Vertices
Priority Queue
Being Examined

Reference implementation of Prim's Algorithm. Select a language tab to view and copy the code.

import heapq

def prim(adj: list[list[tuple[int,int]]]) -> int:
    n = len(adj)
    key    = [float('inf')] * n
    in_mst = [False] * n
    key[0] = 0
    heap = [(0, 0)]   # (weight, node)
    mst_weight = 0
    while heap:
        w, u = heapq.heappop(heap)
        if in_mst[u]:
            continue
        in_mst[u] = True
        mst_weight += w
        for v, edge_w in adj[u]:
            if not in_mst[v] and edge_w < key[v]:
                key[v] = edge_w
                heapq.heappush(heap, (key[v], v))
    return mst_weight

Python — Code Walkthrough

  1. heapq min-heap with (weight, node) tuples

    heap = [(0, 0)]

    Python's heapq is a min-heap. Tuples are compared lexicographically, so (weight, node) naturally gives priority to smaller weights — exactly the order Prim's greedy needs.

  2. continue on already-settled vertex

    if in_mst[u]: continue

    Lazy deletion of stale heap entries. Once a vertex is in the MST, any subsequent pop of it is outdated and skipped.

  3. mst_weight += w on settlement

    in_mst[u] = True; mst_weight += w

    The popped weight w is the minimum edge to u at the time of settlement. Accumulating it gives the total MST weight without needing a separate parent array.

  4. float("inf") as initial key

    key = [float("inf")] * n

    Any real edge weight is less than inf, so the first edge to each vertex will always improve its key — no special cases needed.