# Prim’s Algorithm in C [Program & Algorithm]

Here you will learn about prim’s algorithm in C with a program example.

Prim’s Algorithm is an approach to determine minimum cost spanning tree. In this case, we start with single edge of graph and we add edges to it and finally we get minimum cost tree. In this case, as well, we have n-1 edges when number of nodes in graph are n.We again and again add edges to tree and tree is extended to create spanning tree, while in case of Kruskal’s algorithm there may be more than one tree, which is finally connected through edge to create spanning tree.

### Algorithm

This algorithm creates spanning tree with minimum weight from a given weighted graph.

1. Begin
2. Create edge list of given graph, with their weights.
3. Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
5. Add other edges. While adding an edge take care that the one end of the edge should always be in the skeleton tree and its cost should be minimum.
6. Repeat step 5 until n-1 edges are added.
7. Return.

## Program for Prim’s Algorithm in C

C program for constructing a minimum cost spanning tree of a graph using Prim’s algorithm is given below.

Output

Enter no. of vertices:6

0 3 1 6 0 0
3 0 5 0 3 0
1 5 0 5 6 4
6 0 5 0 0 2
0 3 6 0 0 6
0 0 4 2 6 0

spanning tree matrix:

0 3 1 0 0 0
3 0 0 0 3 0
1 0 0 0 0 4
0 0 0 0 0 2
0 3 0 0 0 0
0 0 4 2 0 0

Total cost of spanning tree=13

#### Time Complexity

Prim’s algorithm contains two nested loops. Each of this loop has a complexity of O (n). Thus, the complexity of Prim’s algorithm for a graph having n vertices = O (n2).

Comment below if you found anything incorrect or missing in above prim’s algorithm in C.

## One thought on “Prim’s Algorithm in C [Program & Algorithm]”

1. bibhu ranjan

please give an explanation on the following snipet of the above code

u=from[v]; //what is u and v here…??

//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges–;
visited[v]=1;

//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}