-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5Prim.cpp
More file actions
76 lines (59 loc) · 1.44 KB
/
Copy path5Prim.cpp
File metadata and controls
76 lines (59 loc) · 1.44 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
#include<bits/stdc++.h>
using namespace std;
void prims(vector<vector<int>>& graph, int n)
{
vector<int> dist(n, INT_MAX);
vector<bool> visited(n, false);
dist[0] = 0;
int totalCost = 0;
// Repeat for all vertices
for(int count=0; count<n; count++)
{
int u = -1;
// Find minimum distance vertex
for(int i=0; i<n; i++)
{
if(visited[i] == false)
{
if(u == -1 || dist[i] < dist[u])
{
u = i;
}
}
}
// Mark as visited
visited[u] = true;
// Add cost
totalCost += dist[u];
// Update neighbours
for(int v=0; v<n; v++)
{
if(graph[u][v] != 0 && visited[v] == false)
{
if(graph[u][v] < dist[v])
{
dist[v] = graph[u][v];
}
}
}
}
cout << "\nMinimum Spanning Tree Cost = "
<< totalCost << endl;
}
int main()
{
int n;
cout << "Enter number of vertices: ";
cin >> n;
vector<vector<int>> graph(n, vector<int>(n));
cout << "Enter adjacency matrix:\n";
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin >> graph[i][j];
}
}
prims(graph, n);
return 0;
}