What is Prim’s algorithm?
Prim’s algorithm is a greedy algorithm i.e., it chooses an optimal path at each point and ultimately finds the shortest path by making a spanning tree.
Algorithm steps
The following steps are used in Prim’s algorithm:
- Remove all self-loops
- Remove all parallel edges. If two nodes have a parallel edge, keep the one which has the least cost
- Select a random node. Check the outgoing edge(s) of that node and pick the edge with the least cost.
- Check each node until all nodes are visited.
The following illustration explains how Prim’s algorithm works:
1 of 9
Time complexity
The time complexity is
where V are the vertices and E are the edges of the graph.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved