DrawCode Algorithm Visualizer • Graph • Medium

Prim's Algorithm (MST)

Tags: Graph, MST, Greedy, Priority Queue

1. One-Liner

Prim builds an MST by starting at an arbitrary root and repeatedly attaching the minimum-weight edge that connects the growing tree to a new vertex.


2. The Problem It Solves

Find a minimum spanning tree: connect all vertices with V−1 edges minimizing total weight — used in network design, clustering, approximation.


3. The Core Idea

Cut property: the lightest edge crossing any cut between tree and non-tree is safe for MST. Prim always picks the lightest edge from the current tree to outside.


4. How It Works (Step-by-Step)

StepAction
1Start with any vertex in MST set; key[v]=min edge weight to tree
2Min-heap: extract min key vertex u not in tree
3For each edge (u,v,w): if v not in tree and w < key[v], update
4Repeat until V−1 edges or heap empty
5parent[] stores MST edges

5. Dry Run Example

Square 0—1 (1), 1—2 (2), 2—3 (3), 3—0 (4), diagonals costly. Prim from 0 picks 0–1, then 1–2, then 2–3 — total 6.


6. Key Properties

PropertyValue
Works onConnected undirected weighted graphs
GreedyYes — cut property
Fibonacci heapTheoretical O(E + V log V)

7. Where It Is Used

DomainUse
Network designMin-cost fiber layout
ApproximationTSP heuristics building blocks

8. Interview Tips

Compare Prim vs Kruskal (node-centric vs edge-centric). Dense graphs prefer Prim with adjacency matrix O(V²).


9. Comparison with Other Algorithms

PrimKruskal
ViewGrow one treeSort all edges
BestDenseSparse (union-find)
DataHeapSort + DSU

10. Complexity

----
TimeO((V+E) log V) with binary heap
SpaceO(V + E)

Implementation Example (PYTHON)

import heapq

def prim(n, edges):
    g = [[] for _ in range(n)]
    for u, v, w in edges:
        g[u].append((v, w)); g[v].append((u, w))
    in_mst = [False] * n
    pq = [(0, 0)]
    total = 0
    while pq:
        w, u = heapq.heappop(pq)
        if in_mst[u]: continue
        in_mst[u] = True
        total += w
        for v, wt in g[u]:
            if not in_mst[v]:
                heapq.heappush(pq, (wt, v))
    return total

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer