-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprims_algo.c
71 lines (65 loc) · 1.37 KB
/
prims_algo.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
// Lab Program 7
// Prim's Algorithm (greedy technique)
// Time Complexity: O(V^2)
#include<stdio.h>
#define INF 9999
int i, j, n, c[20][20], visited[20];
void prims(){
int a, b, min, cost = 0, count = 0;
min = INF;
printf("the minimal spanning tree is: \n");
visited[1] = 1;
while(count < (n -1))
{
min = INF;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
if(visited[i] && (!visited[j]) && min > c[i][j])
{
min = c[i][j];
a = i;
b = j;
}
}
}
printf("%d --> %d = %d\n", a, b, c[a][b]);
cost += c[a][b];
visited[b] = 1;
count++;
}
printf("the total cost is : %d", cost);
}
void main()
{
printf("enter the number of vertices:\n");
scanf("%d", &n);
printf("enter the adjacency matrix:\n");
for(i = 1; i <= n; i++)
{
for(j = 1; j <= n; j++)
{
scanf("%d", &c[i][j]);
visited[i] = 0;
}
}
prims();
}
/*
sample input output:
enter the number of vertices:
5
enter the adjacency matrix:
9999 5 2 9999 9999
5 9999 9999 6 9999
2 9999 9999 1 3
9999 6 1 9999 4
9999 9999 3 4 9999
the minimal spanning tree is:
3 --> 4 = 1
1 --> 3 = 2
3 --> 5 = 3
1 --> 2 = 5
the total cost is : 11
*/