-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprims.cpp
49 lines (49 loc) · 1.17 KB
/
prims.cpp
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
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, i, j, min_cost = 0, no_e = 1, m, a, b;
cout << "Enter no. of nodes:";
cin >> n;
int cost[n + 1][n + 1], visited[n + 1] = {0};
cout << "Enter cost adjacency matrix:" << endl;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
cin >> cost[i][j];
if (cost[i][j] == 0)
{
cost[i][j] = INT_MAX;
}
}
}
visited[1] = 1;
while (no_e < n)
{
m = INT_MAX;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (cost[i][j] < m)
{
m = cost[i][j];
a = i;
b = j;
}
}
}
if (!visited[b])
{
cout << a << " -> " << b << ", cost = " << m << endl;
min_cost += m;
no_e++;
}
visited[b] = 1;
cost[a][b] = INT_MAX;
cost[b][a] = INT_MAX;
}
cout << "Minimum Cost = " << min_cost << endl;
return 0;
}