Skip to content

Commit ebfa887

Browse files
prims-mst-algo
1 parent 2ddb76c commit ebfa887

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed
+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// Program to calculate Minimum Spanning Tree using Prim's algorithm in C++.
2+
#include <iostream>
3+
#include <conio.h>
4+
#define ROW 7
5+
#define COL 7
6+
#define INFINITY 5000
7+
using namespace std;
8+
class MST
9+
{
10+
int graph[ROW][COL], nodes, mini;
11+
12+
public:
13+
MST();
14+
void createGraph();
15+
void primsAlgo();
16+
};
17+
18+
MST ::MST()
19+
{
20+
for (int i = 0; i < ROW; i++)
21+
for (int j = 0; j < COL; j++)
22+
graph[i][j] = 0;
23+
}
24+
25+
void MST ::createGraph()
26+
{
27+
int i, j;
28+
cout << "Enter Total Nodes : ";
29+
cin >> nodes;
30+
cout << "\nEnter Adjacency Matrix : \n";
31+
for (i = 0; i < nodes; i++)
32+
for (j = 0; j < nodes; j++)
33+
cin >> graph[i][j];
34+
35+
for (j = 0; j < nodes; j++)
36+
{
37+
if (graph[i][j] == 0)
38+
graph[i][j] = INFINITY;
39+
}
40+
}
41+
42+
void MST ::primsAlgo()
43+
{
44+
int selected[ROW], i, j, nos_of_edges, x, y;
45+
46+
for (i = 0; i < nodes; i++)
47+
selected[i] = false;
48+
49+
selected[0] = true;
50+
nos_of_edges = 0;
51+
52+
while (nos_of_edges < nodes - 1)
53+
{
54+
mini = INFINITY;
55+
56+
for (i = 0; i < nodes; i++)
57+
{
58+
if (selected[i] == true)
59+
{
60+
for (j = 0; j < nodes; j++)
61+
{
62+
if (selected[j] == false)
63+
{
64+
if (mini > graph[i][j])
65+
{
66+
mini = graph[i][j];
67+
x = i;
68+
y = j;
69+
}
70+
}
71+
}
72+
}
73+
}
74+
selected[y] = true;
75+
cout << "\n"
76+
<< x + 1 << " --> " << y + 1;
77+
nos_of_edges = nos_of_edges + 1;
78+
}
79+
}
80+
81+
int main()
82+
{
83+
MST a;
84+
cout << "\nPrims Algorithm to find Minimum Spanning Tree\n";
85+
a.createGraph();
86+
a.primsAlgo();
87+
getch();
88+
return 0;
89+
}

0 commit comments

Comments
 (0)