Prim Minimum Spanning Tree Algorithm

Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex.

Unlike an edge in Kruskal's algorithm, we add vertex to the growing spanning tree in Prim's algorithm.

The credit of Prim's algorithm goes to Vojtěch Jarník, Robert C. Prim and Edsger W. Dijkstra.

Complexity

Worst case time complexity: Θ(E log V) using priority queues.

Average case time complexity: Θ(E log V) using priority queues.

Best case time complexity: Θ(E log V) using priority queues.

Space complexity: Θ(E + V)

Steps involved are:

Maintain two disjoint sets of vertices. One containing vertices that are in the growing spanning tree and other that are not in the growing spanning tree.

Select the cheapest vertex that is connected to the growing spanning tree and is not in the growing spanning tree and add it into the growing spanning tree. This can be done using Priority Queues. Insert the vertices, that are connected to growing spanning tree, into the Priority Queue.

Check for cycles. To do that, mark the nodes which have been already selected and insert only those nodes in the Priority Queue that are not marked.

Pseudocode

Prim()
S = new empty set
for i = 1 to n
d[i] = inf
while S.size() < n
x = inf
v = -1
for each i in V - S // V is the set of vertices
if x >= d[v]
then x = d[v], v = i
d[v] = 0
S.insert(v)
for each u in adj[v]
do d[u] = min(d[u], w(v,u))