Repository navigation
Expand file tree
/
Copy pathprim.c
More file actions
93 lines (79 loc) · 1.45 KB
/
Copy pathprim.c
File metadata and controls
93 lines (79 loc) · 1.45 KB
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
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<limits.h>
int v;
int minkey(int key[],int mstset[]){
int min=INT_MAX,min_index;
for(int count=0;count<v;count++){
if(mstset[count]==0 && key[count]<min)
{
min=key[count];
min_index=count;
}
}
return min_index;
}
void primMst(int graph[][v]){
int parent[v];
int key[v];
int mstset[v];
for(int i=0;i<v;i++)
{
key[i]=INT_MAX;
parent[i]=-1;
mstset[i]=0;
}
key[0]=0;
parent[0]=-1;
for(int count=0;count<v-1;count++){
int u=minkey(key,mstset);
mstset[u]=1;
for(int i=0;i<v;i++){
if(graph[u][i] && mstset[i]==0 &&graph[u][i]<key[i]){
key[i]=graph[u][i];
parent[i]=u;
}
}
}
printgraph(parent,graph);
}
void printgraph(int parent[],int graph[][v]){
int sum=0;
printf("Edge \t edge weight \t weight\n");
for(int i=1;i<v;i++)
{
sum+=graph[i][parent[i]];
printf("%d----%d\t %d\t %d\n",parent[i],i,graph[i][parent[i]],sum);
}
}
int main(int argc,char* argv[]){
if(argc<2){
printf("give the file that consists of input\n");
return 1;
}
FILE* fp= fopen(argv[1],"r");
if(fp==NULL){
printf("file doesnot exists\n");
return 1;
}
if(fscanf(fp,"%d",&v)==0){
printf("error while reading number of vertices\n");
return 1;
}
//reading is completed
int graph[v][v];
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
fscanf(fp,"%d",&graph[i][j]);
}
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
printf("%d ",graph[i][j]);
printf("\n");
}
primMst(graph);
return 0;
}