1. Min-heap by weight
The heap always surfaces the cheapest edge crossing out of the tree.
const heap = new MinHeap((x, y) => x[0] - y[0])Typorithm · medium
Step 1 of 8 · intro card
Graph Algorithms
Grow one tree from a start node using a min-heap of (weight, node) edges, always adding the cheapest edge to an unvisited node.
Prim's builds a minimum spanning tree by expanding a single growing tree outward.
A min-heap holds candidate edges; the cheapest edge to a node outside the tree is taken next.
Adding a node pushes its neighbors' edges, refreshing the frontier of crossing edges.
Min-heap orders edges by weight.
Pop the cheapest edge to a new node.
Push neighbors after adding a node.
function primMst(n, graph, start) {
const inTree = new Array(n).fill(false);
const heap = new MinHeap((x, y) => x[0] - y[0]);
heap.push([0, start]);
let total = 0;
let used = 0;
while (heap.size() > 0 && used < n) {
const [weight, node] = heap.pop();
if (inTree[node]) continue;
inTree[node] = true;
total += weight;
used += 1;
for (const [next, w] of graph[node]) {
if (!inTree[next]) heap.push([w, next]);
}
}
return used === n ? total : null;
}Connect each part of the code to the concept before you type.
The heap always surfaces the cheapest edge crossing out of the tree.
const heap = new MinHeap((x, y) => x[0] - y[0])Begin the tree at the start node with zero cost.
heap.push([0, start])Repeatedly take the cheapest edge to a node not yet in the tree.
const [weight, node] = heap.pop()A node may sit in the heap more than once; ignore it once it is already in the tree.
if (inTree[node]) continueAdding a node exposes new crossing edges for the heap to consider.
if (!inTree[next]) heap.push([w, next])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUndirected graph · start A · edges A–B:4, A–D:2, B–C:3, B–E:1, D–E:5, E–F:2, C–F:4
Follow temporary values, local state and supporting structures at this step.
selected edges0 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state