Prim's Algorithm
Special thanks to Arin for writing this page!
Conceptual Overview
Detailed Breakdown
Useful Properties/Invariants
Pseudocode
public class Prims() {
public Prims() {
PQ = new PriorityQueue<>();
edgeTo = new Edge[numVertices];
distTo = new Dist[numVertices];
marked = new boolean[numVertices];
}
public void doPrims() {
PQ.add(sourceVertex, 0);
for(v : allOtherVertices) {
PQ.add(v, INFINITY);
}
while (!PQ.isEmpty()) {
Vertex p = PQ.removeSmallest();
marked[p] = true;
relax(p);
}
}
public void relax(Vertex p) {
for (q : p.neighbors()) {
if (marked[q]) { continue; }
if (q.edgeWeight < distTo[q]) {
distTo[q] = q.edgeWeigth;
edgeTo[q] = p;
PQ.changePriority(q, distTo[q]);
}
}
}
}Runtime Analysis
Demo
Last updated