In graph theory, Prim’s algorithm is a solution to the minimum spanning tree problem, i.e., given a positive weighted connected undirected graph , it finds an MST such that the edges have the minimum weight. It does this by using a greedy approach (much like Dijkstra’s algorithm).
Implementation and analysis
The pseudocode for Prim’s is given by:
Step-by-step, Prim’s algorithm:
- Sets the key of each vertex to , except for the root which is set to 0 to indicate that it’s been processed.
- Set the parent of each vertex to NIL, and insert each vertex into a min-priority queue .
- Then, the algorithm begins a loop.
- It identifies the lowest weight edge (i.e., a light edge) that crosses the cut , then removes it from the priority queue and add it to the set of vertices in the tree.
- The
for
loop updates the key and parent attributes of every vertex adjacent to but not in the tree, which maintains the algorithm’s loop invariant, - Then, if the edge weight is less than the key of , it is overwritten with the edge weight, and
Decrease-Key
updates the key value in the priority queue.
The time complexity is primarily dominated by the while
loop and its contents. The outer loop runs in time, Extract-Min
takes (assuming a binary heap), the for
loop that updates the key/parent attributes, and Decrease-Key
also takes . So the total time complexity is , which is asymptotically the same as Kruskal’s algorithm.
Tutorial
ATaC MST such that . gives us a cycle cycle, , , which is spanning contradiction somewhere let be max edge weight and path connecting where ATaC MST such that let be an edge on path that is not in i.e., u → v via e and u ← v via p consider which must have a cycle, and cycle includes by how is defined so contradiction
looks pretty similar to greedy proofs