Points to remember
- Prim’s algorithm is specifically designed to find the MST of a weighted undirected graph*.
- Dijkstra’s algorithm, on the other hand, is used to find the shortest path from a single source vertex to all other vertices in a weighted graph
- The Minimum Spanning Tree is a subset of the edges of the graph that connects all the vertices together, without any cycles, and with the minimum possible total edge weight. ⭐️
- When you have a graph with non-negative edge weights use Prims.
- Run PRIM’s from an arbitrary node.⭐️
When is Prim’s Algorithm Used?
- Connect a set of points (or vertices) with the least total cost, such as in network design (like laying cables, building roads, etc.).
- Find the MST in a graph where edge weights are available, and the graph is undirected and connected.
Difference b/w Dijkstra Algorithm and Prims Algorithm:
- Dijkstra’s algorithm adds up the edge weights to get the total distance from the source to each node, making decisions based on these cumulative distances.
- Prim’s algorithm only considers the edge weights directly and chooses the smallest edge that connects an unvisited vertex to the growing MST. It doesn’t accumulate weights like Dijkstra’s algorithm; it simply ensures that the next edge added is the lightest available that connects to the MST.
Code
Run this to see how PRIMS algorithm find MST.