Minimal Spanning Tree using Prim’s Algorithm

Algorithm

Input	No. of  Vertex , Edges weights between vertices
Output	Minimum spanning tree of graph
Complexity	O(E + V lg V)

MST-PRIM(G, w, r)
[This algorithm takes a graph G as an input and w is the weight. Here V[G] are the set of vertices of a graph. (u,v) is an edge between any two vertices u and v. Finally it returns a set A having edges for Minimum spanning tree of G. Here for each vertex key[v] is the minimum weight of any edge connecting v to a vertex in the tree; by convention, key[v] = ∞ if there is no such edge. The field Ï€[v] names the parent of v in the tree. Q is queue used. Adj[u] is adjoint vertices of vertex u ] 

1. for each u ε V [G]
2. 	do key[u] ← ∞
3.		 Ï€[u] ← NIL
4. key[r] ← 0
5. Q ← V [G]
6. while Q ≠ Ø
7. 	do u ← EXTRACT-MIN(Q)
8.		 for each v ε Adj[u]
9. 			do if v ε Q and w(u, v) < key[v]
10.				 then π[v] ← u
11. 					key[v] ← w(u, v)


Algorithm Description

C Code


//WAP to implement Prim's algorithm

#include<stdio.h>
#include<conio.h>
#include"stdlib.h"
struct node
{
	int key;
	int data;
	struct node *par;
};
struct node *n[20];
struct edge
{
	int wt;
	struct node *src,*des;
};
struct edge *e[20][20];
void makeset(int i)
{
     n[i]=(struct node *)malloc(sizeof(struct node));
     n[i]->data=i;
     n[i]->key=9999;
     n[i]->par=NULL;
}
int main()
{
	int tn,i,adm[20][20],q[20],s,j,w,temp,k;
	printf("Enter the total no. of nodes ");
	scanf("%d",&tn);
	for(i=0;i<=tn;i++)
	{
		for(j=0;j<=tn;j++)
		{
			adm[i][j]=0;
		}
	}
	printf("\nEnter the weights for the following edges ::\n");
	for(i=1;i<=tn;i++)
	{
		makeset(i);
		q[i]=i;
		for(j=i+1;j<=tn;j++)
		{
			printf("%d  %d: ",i,j);
			scanf("%d",&w);
			if(w==0)
			w=9999;
			e[i][j]=(struct edge *)malloc(sizeof(struct edge));
			e[i][j]->wt=w;         
			e[i][j]->src=n[i];    
			e[i][j]->des=n[j];    
			adm[i][j]=1;
			adm[j][i]=1;
		}
	}
	j=1;
	while(j<=tn)
	{
		q[j]=0;
		temp=j;
		for(k=1;k<=tn;k++)
		{
			if(adm[temp][k]==1 && q[k]==k)
			{
				if(e[temp][k]->wtkey)
				{
					n[k]->par=n[temp];  
					n[k]->key=e[temp][k]->wt;
				}
			}
		}
	j++;
	}
	for(j=2;j<=tn;j++)
	{
		k=(n[j]->par)->data;
		printf("output is %d : %d - %d\n",k,j,e[k][j]->wt);
	}
}