-
Notifications
You must be signed in to change notification settings - Fork 495
/
Copy pathPrims.cpp
85 lines (66 loc) Β· 1.87 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
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
#include<iostream>
using namespace std;
#define V 5
int findDistance(int distance[],bool check[]){
int minimum= INT_MAX, min_index;
for (int i = 0; i < V; i++)
if (check[i] == false && distance[i] < minimum)
minimum = distance[i], min_index = i;
return min_index;
}
void printMST(int parent[], int graph[V][V])
{
cout<<"Edge \tWeight\n";
for (int i = 1; i < V; i++)
cout<<parent[i]<<" - "<<i<<" \t"<<graph[i][parent[i]]<<" \n";
}
void printMST(int graph[V][V]){
// assign distance
int distance[V];
//To store the parent visited vertex
int parent[V];
//To mark weather vertex is visited or not
bool check[V];
for(int i=0;i<V;i++){
check[i]=false;
//Assign a very large no. to distance assume infnity
distance[i]= INT_MAX;
}
//as root node of parent won't have any parent
parent[0]=-1;
// 0 as root node
distance[0]=1;
//To find out the Visited Vertex
int Edges = V-1;//no of edges in spanning tree
for(int i=0;i<Edges;i++){
int minimum = findDistance(distance,check);
check[minimum]= true;
//If we encounter less Value then we haVe to update that
//so
for(int j=0;j<V;j++){
if(graph[i][j] && check[j]==false && graph[i][j]<distance[j]){
minimum = graph[i][j];
parent[j]=i;
}
}
}
// print the constructed MST
printMST(parent, graph);
}
int main(){
/* Let us create the following graph
(0)-2-(1)-3-(2)
| |
6 |---|
||-|
(3)---9---(4)
*/
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
//To print
printMST(graph);
return 0;
}