-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprim_b.c
88 lines (68 loc) · 1.63 KB
/
prim_b.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
#include <stdio.h>
#define MAX 100
#define INF 99999
int mat[MAX][MAX];
int parent[MAX];
int num;
int IsMST_Full()
{
int k;
for(k=0; k < num; k++) {
if (parent[k] == INF)
return 0;
}
return 1;
}
int IsVertexInMST(int vertex)
{
if(parent[vertex] != INF)
return 1;
else
return 0;
}
int main()
{
int r, c, k, l, i;
printf("Welcome to Prims's..\n");
printf("Enter number of nodes..\n");
scanf("%d", &num);
for(r=0; r<num; r++) {
for(c=0; c<num; c++) {
scanf("%d", &mat[r][c]);
}
}
for(r=0; r<num; r++) {
for(c=0; c<num; c++) {
printf("[%d]", mat[r][c]);
}
printf("\n");
}
for(i=0; i < num; i++) {
parent[i] = INF;
}
parent[0] = 0;
while(!IsMST_Full()) {
int mincost = 0;
int parentnode;
int childnode;
for(k=0; k < num; k++) {
if (IsVertexInMST(k)) {
for(l=0; l < num; l++) {
if(mat[k][l] !=0 && !IsVertexInMST(l)) {
if (mat[k][l] < mincost || mincost ==0) {
mincost = mat[k][l];
childnode = l;
parentnode = k;
}
}
}
}
}
printf("%d %d\n", childnode, parentnode);
parent[childnode] = parentnode;
}
printf(" Edge Wight\n");
printf("====================\n");
for(k=0; k < num; k++)
printf("%d %d --> %d\n", parent[k], k, mat[parent[k]][k]);
}