From 23231b21f7a76386d60a9e4b240a6fa4b68b0b61 Mon Sep 17 00:00:00 2001 From: NoobCoderReturns <112306726+NoobCoderReturns@users.noreply.github.com> Date: Mon, 6 Oct 2025 20:00:18 +0530 Subject: [PATCH] Created Kruskal's Algorithm --- CPP/graph/Kruskal's Algorithm | 114 ++++++++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100644 CPP/graph/Kruskal's Algorithm diff --git a/CPP/graph/Kruskal's Algorithm b/CPP/graph/Kruskal's Algorithm new file mode 100644 index 0000000..32c3d7e --- /dev/null +++ b/CPP/graph/Kruskal's Algorithm @@ -0,0 +1,114 @@ +#include +using namespace std; + +/* + Kruskal's Algorithm to find the Minimum Spanning Tree (MST) + ----------------------------------------------------------- + - Works on edge list representation + - Sorts edges by weight (ascending) + - Uses Union-Find (Disjoint Set Union) to avoid cycles +*/ + +class DSU { +public: + vector parent, rank; + + DSU(int n) { + parent.resize(n); + rank.resize(n, 0); + for (int i = 0; i < n; i++) + parent[i] = i; + } + + int find(int x) { + if (x == parent[x]) + return x; + return parent[x] = find(parent[x]); // Path compression + } + + bool unite(int x, int y) { + int px = find(x); + int py = find(y); + + if (px == py) + return false; // Same component, adding this edge creates a cycle + + // Union by rank + if (rank[px] < rank[py]) + parent[px] = py; + else if (rank[py] < rank[px]) + parent[py] = px; + else { + parent[py] = px; + rank[px]++; + } + + return true; + } +}; + +class Solution { +public: + // Each edge: {weight, {u, v}} + int kruskalMST(int V, vector>& edges) { + // Sort edges by weight + sort(edges.begin(), edges.end(), + [](const vector& a, const vector& b) { + return a[2] < b[2]; + }); + + DSU dsu(V); + int mstWeight = 0; + vector> mstEdges; + + for (auto& e : edges) { + int u = e[0], v = e[1], w = e[2]; + + if (dsu.unite(u, v)) { + mstWeight += w; + mstEdges.push_back({u, v, w}); + } + } + + // Print MST edges + cout << "Edges in the Minimum Spanning Tree:\n"; + for (auto& e : mstEdges) + cout << e[0] << " - " << e[1] << " : " << e[2] << "\n"; + + return mstWeight; + } +}; + +int main() { + /* + Example Graph: + Vertices = 4 + Edges = 5 + Edge list: (u, v, w) + 0 -- 1 (10) + 0 -- 2 (6) + 0 -- 3 (5) + 1 -- 3 (15) + 2 -- 3 (4) + + Expected MST: + Edges -> (2,3,4), (0,3,5), (0,1,10) + Total Weight = 19 + */ + + int V = 4; + vector> edges = { + {0, 1, 10}, + {0, 2, 6}, + {0, 3, 5}, + {1, 3, 15}, + {2, 3, 4} + }; + + Solution sol; + int totalWeight = sol.kruskalMST(V, edges); + + cout << "\nTotal weight of MST: " << totalWeight << endl; + + return 0; +}