Implement Prim’s Algorithm
Pattern: Minimum spanning tree
Prim's method grows the tree from vertex 0. Keep the edges leaving the tree in a min-heap; repeatedly take the cheapest one that reaches a new vertex. This guide returns the edges as [from, to, weight] in the order they are added.
The problem
Return the edges of a minimum spanning tree as [vertex already in the tree, new vertex, weight], in the order Prim's
method adds them, starting from vertex 0. Weights are distinct. Vertices are numbered from 0 and each edge is [u, v, weight].
Think first
- Where does the tree start?
- Which edges are candidates?
- How is Prim like Dijkstra?
Hints
Brute force, and why it fails
Scan all crossing edges each time: O(V × E).
The key insight
A heap of crossing edges always gives the cheapest safe edge next.
Dry run
Take the 5-vertex example with edges 0-1 (2), 0-3 (6), 1-2 (3), 1-3 (8), 1-4 (5), 2-4 (7), 3-4 (9). The tree starts as {0}; the heap holds 0-1 (2) and 0-3 (6).
The plan
inTree = {0}; heap = edges of 0
while heap: (w, a, b) = pop; if b in tree: skip; add b; record [a, b, w]; push b's edges
Complexity
- Time
O(E log E)- Space
O(V + E)
Each edge is pushed at most twice.
Edge cases
- A single vertex with no edges.
- A graph in several pieces.
- Two vertices joined by one edge.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> primMST(int n, int[][] edges) {
List<List<int[]>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
for (int[] e : edges) { adj.get(e[0]).add(new int[]{e[1], e[2]}); adj.get(e[1]).add(new int[]{e[0], e[2]}); }
boolean[] inTree = new boolean[n];
inTree[0] = true; // grow the tree from vertex 0
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {weight, from, to}
for (int[] e : adj.get(0)) pq.add(new int[]{e[1], 0, e[0]});
List<List<Integer>> tree = new ArrayList<>();
while (!pq.isEmpty()) {
int[] top = pq.poll();
if (inTree[top[2]]) continue; // both ends already inside
inTree[top[2]] = true;
tree.add(Arrays.asList(top[1], top[2], top[0])); // the cheapest edge crossing out of the tree
for (int[] e : adj.get(top[2])) if (!inTree[e[0]]) pq.add(new int[]{e[1], top[2], e[0]});
}
return tree;
}
}C++
class Solution {
public:
vector<vector<int>> primMST(int n, vector<vector<int>>& edges) {
vector<vector<pair<int, int>>> adj(n);
for (const vector<int>& e : edges) { adj[e[0]].push_back(make_pair(e[1], e[2])); adj[e[1]].push_back(make_pair(e[0], e[2])); }
vector<bool> inTree(n, false);
inTree[0] = true; // grow the tree from vertex 0
priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq; // {weight, from, to}
for (const pair<int, int>& e : adj[0]) pq.push(vector<int>{e.second, 0, e.first});
vector<vector<int>> tree;
while (!pq.empty()) {
vector<int> top = pq.top();
pq.pop();
if (inTree[top[2]]) continue; // both ends already inside
inTree[top[2]] = true;
tree.push_back(vector<int>{top[1], top[2], top[0]}); // the cheapest edge crossing out of the tree
for (const pair<int, int>& e : adj[top[2]]) if (!inTree[e.first]) pq.push(vector<int>{e.second, top[2], e.first});
}
return tree;
}
};Python
import heapq
class Solution:
def primMST(self, n: int, edges: list[list[int]]) -> list[list[int]]:
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w))
adj[v].append((u, w))
in_tree = [False] * n
in_tree[0] = True # grow the tree from vertex 0
pq = [(w, 0, v) for v, w in adj[0]] # (weight, from, to)
heapq.heapify(pq)
tree = []
while pq:
w, a, b = heapq.heappop(pq)
if in_tree[b]:
continue # both ends already inside
in_tree[b] = True
tree.append([a, b, w]) # the cheapest edge crossing out of the tree
for v, wt in adj[b]:
if not in_tree[v]:
heapq.heappush(pq, (wt, b, v))
return treeCommon mistakes
- Using the distance from vertex 0 as the key (that is Dijkstra).
- Recording edges whose new end is already in the tree.