Menu
Coddy logo textTech

Prim's Algorithm

Last updated

Prim's algorithm builds a minimum spanning tree (MST) - the cheapest set of edges connecting every node with no cycles - by growing a single tree outward from a starting node. At each step it looks at every edge crossing from the tree to a node outside it, and adds the cheapest one. Press play above to watch the tree expand, always taking the lowest-weight edge that reaches a new node.

Because it always picks the minimum crossing edge, each addition is safe (guaranteed to be part of some MST). With a binary-heap priority queue keyed by the cheapest edge to each outside node, Prim runs in O(E log V). It contrasts with Kruskal, which sorts all edges globally instead of growing one connected tree.

Time & space complexity

ImplementationComplexityNotes
Binary heapO(E log V)Priority queue of crossing edges
Adjacency matrixO(V²)Simpler; good for dense graphs
SpaceO(V + E)Tree membership + priority queue
Best forDense graphsGrows from a single start node

Step by step

StepWhat happens
1Start the tree with any single node.
2Look at all edges crossing from the tree to a node outside it.
3Pick the crossing edge with the smallest weight.
4Add that edge and its new node to the tree.
5Repeat until every node is in the tree.

Worked example

Building the MST of a 4-node graph with edges A-B=1, A-C=3, B-C=2, B-D=4, C-D=5, starting from A:

StepTreeCrossing edgesChosen edge
1{A}A-B=1, A-C=3A-B (weight 1)
2{A, B}A-C=3, B-C=2, B-D=4B-C (weight 2)
3{A, B, C}B-D=4, C-D=5B-D (weight 4)
4{A, B, C, D}none - all nodes in treedone: MST weight 1+2+4 = 7

When to use Prim's algorithm

Use it whenAvoid it when
You need a minimum spanning tree of a connected, undirected weighted graph.The graph is directed or you need shortest paths - use Dijkstra or Bellman-Ford instead.
The graph is dense (E close to ); the O(V²) matrix form is simple and fast.The graph is sparse and edges are already sorted or easy to sort - Kruskal is often simpler.
You want the tree to grow from one region outward (e.g. incremental network layout).The graph is disconnected - Prim only spans one component; you need a minimum spanning forest.
You already have an adjacency structure and a priority queue available.You need to detect cycles across a global edge set - union-find (Kruskal) fits that shape better.

Prim's Algorithm code

A clean, runnable Prim's Algorithm implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Prim's Algorithm code in Python

Python
1import heapq2
3
4def prim(graph, start):5    visited = {start}6    heap = [(w, start, v) for v, w in graph[start]]7    heapq.heapify(heap)8    mst, total = [], 09    while heap and len(visited) < len(graph):10        w, u, v = heapq.heappop(heap)11        if v in visited:12            continue13        visited.add(v)14        mst.append((u, v, w))15        total += w16        # Offer the new node's edges to the frontier17        for neighbor, weight in graph[v]:18            if neighbor not in visited:19                heapq.heappush(heap, (weight, v, neighbor))20    return mst, total21
22
23graph = {24    "A": [("B", 4), ("C", 1)],25    "B": [("A", 4), ("C", 3), ("D", 2)],26    "C": [("A", 1), ("B", 3), ("D", 5)],27    "D": [("B", 2), ("C", 5), ("E", 7)],28    "E": [("D", 7)],29}30
31mst, total = prim(graph, "A")32for u, v, w in mst:33    print(f"{u} - {v} (weight {w})")34print("Total MST weight:", total)
Run this code in the Python Playground

Prim's Algorithm FAQ

What is the time complexity of Prim's algorithm?
With a binary-heap priority queue, Prim runs in O(E log V). A simpler adjacency-matrix version that scans for the minimum crossing edge each step is O(V²), which can be faster on dense graphs. Both use O(V + E) space.
What is the difference between Prim's and Kruskal's algorithm?
Both find a minimum spanning tree greedily. Prim grows one connected tree from a start node, repeatedly adding the cheapest edge that leaves the tree (using a priority queue). Kruskal considers all edges sorted by weight and adds the cheapest that doesn't form a cycle (using union-find). Prim is often preferred on dense graphs, Kruskal on sparse ones.
Does Prim's algorithm always find the optimal MST?
Yes. At every step the cheapest edge crossing the current tree is safe to add - it belongs to some minimum spanning tree (the cut property). Repeatedly adding safe edges yields a genuine minimum spanning tree, provided the graph is connected.
When should I use Prim's algorithm instead of Kruskal's?
Reach for Prim when the graph is dense, because its O(V²) adjacency-matrix form avoids sorting all E edges and grows one tree from a start node. Kruskal shines on sparse graphs where sorting the edge list is cheap and union-find keeps cycle checks fast. Both produce a correct MST, so the choice is mainly about edge density and which data structures you already have.
Does the starting node affect the resulting MST?
No - the total weight of the MST is the same no matter which node you start from, because a connected graph's minimum spanning tree weight is unique. The specific edges can differ only when several edges share the same weight and multiple MSTs exist. Otherwise Prim reaches the exact same tree regardless of start node.
Can Prim's algorithm handle disconnected graphs?
Not directly. Prim grows a single tree, so it only spans the connected component containing the start node and leaves the rest untouched. To cover every component you would run Prim from an unvisited node repeatedly, producing a minimum spanning forest rather than one tree.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED