Let’s say we have 8 houses. We want to setup telephone lines between these houses. The edge between the houses represent the cost of setting line between two houses.


Our task is to set up lines in such a way that all the houses are connected and the cost of setting up the whole connection is minimum. Now how do we find that out? We can use Prim’s Algorithm.

Prim’s Algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. This means it finds a subset of the edges that forms a tree that includes every node, where the total weight of all the edges in the tree are minimized. The algorithm was developed in 1930 by Czech mathematician Vojtěch Jarník and later rediscovered and republished by computer scientist Robert Clay Prim in 1957 and Edsger Wybe Dijkstra in 1959. It is also known as DJP algorithm, Jarnik’s algorithm, Prim-Jarnik algorithm or Prim-Dijsktra algorithm.

Now let’s look at the technical terms first. If we create a graph, S using some nodes and edges of an undirected graph G, then S is called a subgraph of the graph G. Now S will be called a Spanning Tree if and only if:

There can be many Spanning Tree‘s of a graph. The Minimum Spanning Tree of a weighted undirected graph is a tree, such that sum of the weight of the edges is minimum. Now we’ll use Prim’s algorithm to find out the minimum spanning tree, that is how to set up the telephone lines in our example graph in such way that the cost of set up is minimum.

At first we’ll select a source node. Let’s say, node-1 is our source. Now we’ll add the edge from node-1 that has the minimum cost to our subgraph. Here we mark the edges that are in the subgraph using the color blue. Here 1-5 is our desired edge.


Now we consider all the edges from node-1 and node-5 and take the minimum. Since 1-5 is already marked, we take 1-2.


This time, we consider node-1, node-2 and node-5 and take the minimum edge which is 5-4.


The next step is important. From node-1, node-2, node-5 and node-4, the minimum edge is 2-4. But if we select that one, it’ll create a cycle in our subgraph. This is because node-2 and node-4 are already in our subgraph. So taking edge 2-4 doesn’t benefit us. We’ll select the edges in such way that it adds a new node in our subgraph. So we select edge 4-8.


If we continue this way, we’ll select edge 8-6, 6-7 and 4-3. Our subgraph will look like:


This is our desired subgraph, that’ll give us the minimum spanning tree. If we remove the edges that we didn’t select, we’ll get: