-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprismAlgorithm.cpp
More file actions
122 lines (109 loc) · 2.65 KB
/
Copy pathprismAlgorithm.cpp
File metadata and controls
122 lines (109 loc) · 2.65 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <iostream>
#include <iomanip>
#define INFINITY 999
using namespace std;
class PrismAlgorithm
{
private:
int numberOfVertices;
int ** adjMatrix;
public:
PrismAlgorithm();
~PrismAlgorithm();
void createAdjTable();
void displayAdjTable();
void prims();
};
PrismAlgorithm::PrismAlgorithm()
{
numberOfVertices = 0;
adjMatrix = NULL;
}
PrismAlgorithm::~PrismAlgorithm()
{
numberOfVertices = 0;
adjMatrix = NULL;
}
void PrismAlgorithm::createAdjTable()
{
cout<<"Enter number of vertices in the graph :";
cin>>numberOfVertices;
adjMatrix = new int * [numberOfVertices];
for(int i=0;i<numberOfVertices;i++)
adjMatrix[i]=new int [numberOfVertices];
for(int i=0;i<numberOfVertices;i++)
{
for(int j=0;j<numberOfVertices;j++)
adjMatrix[i][j]=INFINITY;
}
int v1,v2;
char ch;
int weight;
do
{
cout<<"Enter edge : ";
cin>>v1>>v2;
cout<<"Enter Weight : ";
cin>>weight;
adjMatrix[v1][v2]=adjMatrix[v2][v1]=weight;
cout<<"Enter Y to add more edges :";
cin>>ch;
}while(ch=='y' or ch=='Y');
}
void PrismAlgorithm::displayAdjTable()
{
for(int i=0;i<numberOfVertices;i++)
{
for(int j=0;j<numberOfVertices;j++)
cout<<setw(3)<<adjMatrix[i][j]<<" ";
cout<<endl;
}
}
void PrismAlgorithm::prims()
{
int VisitCount = 0;
int totalWeight = 0;
int * visited = new int [numberOfVertices];
int minimumWeight;
int minVertex[2];
for(int i=0;i<numberOfVertices;i++)
visited[i]=0;
int vertex;
cout<<"Enter Source Vertex : ";
cin>>vertex;
visited[vertex] = 1;
VisitCount = 1;
while(VisitCount!=numberOfVertices)
{
minimumWeight = INFINITY;
for(vertex = 0;vertex < numberOfVertices;vertex++)
{
if(visited[vertex] == 1)
{
for(int i=0;i<numberOfVertices;i++)
{
if(adjMatrix[vertex][i] != INFINITY and visited[i] == 0)
{
if(adjMatrix[vertex][i] < minimumWeight)
{
minimumWeight = adjMatrix[vertex][i];
minVertex[0] = i;
minVertex[1] = adjMatrix[vertex][i];
}
}
}
}
}
totalWeight = totalWeight + minVertex[1];
visited[minVertex[0]]=1;
VisitCount++;
}
cout<<"Minimum Cost = "<<totalWeight<<endl;
}
int main()
{
PrismAlgorithm obj;
obj.createAdjTable();
obj.displayAdjTable();
obj.prims();
}