-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPRIM.C
95 lines (91 loc) · 2.2 KB
/
PRIM.C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
AIM:Prim's
Name:
Roll no:
*/
#include<stdio.h>
#include<conio.h>
const int maxint=32767;
void readgraph(int adj[10][10],int e)
{
int i,j,s,d;
printf("Enter the cost of each edge of graph.....\n");
for(i=1;i<=e;i++)
{
printf("Enter the source and desestination node:");
scanf("%d%d",&s,&d);
printf("Enter cost of edge :");
scanf("%d",&adj[s][d]);
adj[d][s]=adj[s][d];
}
}
void primst(int adj[10][10],int visited[10],int n)
{
int i,j,nd,min,ss,sd,x,y;
int cost=0;
visited[1]=1;
nd=1;
while(nd<n)
{
for(i=1,min=maxint;i<=n;i++)
for(j=1;j<=n;j++)
if(adj[i][j]<min)
if(visited[i]!=0)
{
min=adj[i][j];
x=ss=i;
y=sd=j;
}
if(visited[ss]==0 || visited[sd]==0)
{
printf("Edge of MST %d:{%d-%d} and cost =%d\n",nd++,x,y,min);
cost+=min;
visited[y]=1;
}
adj[x][y]=adj[y][x]=maxint;
}
printf("Minimum cost of given Spanning Tree =%d",cost);
}
void main()
{
int adj[10][10],visited[10],i,j,n,eg;
clrscr();
printf("Enter the total no. of nodes of graph:");
scanf("%d",&n);
for(i=1;i<=n;i++)
visited[i]=0;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
adj[i][j]=maxint;
printf("Enter total no. of edges of graph:");
scanf("%d",&eg);
readgraph(adj,eg);
primst(adj,visited,n);
getch();
}
/*OUTPUT:
Enter the total no. of nodes of graph:6
Enter total no. of edges of graph:8
Enter the cost of each edge of graph.....
Enter the source and desestination node:1 2
Enter cost of edge :5
Enter the source and desestination node:1 5
Enter cost of edge :9
Enter the source and desestination node:1 3
Enter cost of edge :8
Enter the source and desestination node:2 3
Enter cost of edge :3
Enter the source and desestination node:3 4
Enter cost of edge :7
Enter the source and desestination node:4 6
Enter cost of edge :2
Enter the source and desestination node:5 6
Enter cost of edge :1
Enter the source and desestination node:5 3
Enter cost of edge :4
Edge of MST 1:{1-2} and cost =5
Edge of MST 2:{2-3} and cost =3
Edge of MST 3:{3-5} and cost =4
Edge of MST 4:{5-6} and cost =1
Edge of MST 5:{6-4} and cost =2
Minimum cost of given Spanning Tree =15 */