forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KruskalsAlgorithm.cpp
76 lines (60 loc) · 1.72 KB
/
KruskalsAlgorithm.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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int src, dest, weight;
};
class Graph {
private:
int V;
vector<Edge> edges;
public:
Graph(int vertices) : V(vertices) {}
void addEdge(int src, int dest, int weight) {
edges.push_back({src, dest, weight});
}
int findParent(vector<int>& parent, int vertex) {
if (parent[vertex] == -1)
return vertex;
return findParent(parent, parent[vertex]);
}
void unionVertices(vector<int>& parent, int x, int y) {
int rootX = findParent(parent, x);
int rootY = findParent(parent, y);
parent[rootX] = rootY;
}
void kruskalMST() {
// Sort edges by weight
sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
return a.weight < b.weight;
});
vector<int> parent(V, -1);
vector<Edge> mst;
for (const Edge& edge : edges) {
int rootSrc = findParent(parent, edge.src);
int rootDest = findParent(parent, edge.dest);
if (rootSrc != rootDest) {
mst.push_back(edge);
unionVertices(parent, rootSrc, rootDest);
}
}
cout << "Minimum Spanning Tree (Kruskal's Algorithm):\n";
for (const Edge& edge : mst) {
cout << edge.src << " - " << edge.dest << " : " << edge.weight << "\n";
}
}
};
int main() {
Graph g(6); // Number of vertices
// Adding edges with weights
g.addEdge(0, 1, 4);
g.addEdge(0, 2, 4);
g.addEdge(1, 2, 2);
g.addEdge(1, 3, 5);
g.addEdge(2, 3, 1);
g.addEdge(2, 4, 3);
g.addEdge(3, 4, 7);
g.kruskalMST();
return 0;
}