|
| 1 | +package com.thealgorithms.graph; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +/** |
| 5 | + * Implements Kruskal's Algorithm to find the Minimum Spanning Tree (MST) |
| 6 | + * of a connected, undirected, weighted graph using Union-Find. |
| 7 | + */ |
| 8 | +public class KruskalMinimumSpanningTree { |
| 9 | + |
| 10 | + static class Edge implements Comparable<Edge> { |
| 11 | + int src, dest, weight; |
| 12 | + |
| 13 | + Edge(int src, int dest, int weight) { |
| 14 | + this.src = src; |
| 15 | + this.dest = dest; |
| 16 | + this.weight = weight; |
| 17 | + } |
| 18 | + |
| 19 | + @Override |
| 20 | + public int compareTo(Edge other) { |
| 21 | + return Integer.compare(this.weight, other.weight); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + static class UnionFind { |
| 26 | + int[] parent; |
| 27 | + |
| 28 | + UnionFind(int size) { |
| 29 | + parent = new int[size]; |
| 30 | + Arrays.fill(parent, -1); |
| 31 | + } |
| 32 | + |
| 33 | + int find(int node) { |
| 34 | + if (parent[node] < 0) return node; |
| 35 | + return parent[node] = find(parent[node]); |
| 36 | + } |
| 37 | + |
| 38 | + boolean union(int u, int v) { |
| 39 | + int rootU = find(u); |
| 40 | + int rootV = find(v); |
| 41 | + if (rootU == rootV) return false; |
| 42 | + parent[rootV] = rootU; |
| 43 | + return true; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public static List<Edge> kruskalMST(List<Edge> edges, int vertices) { |
| 48 | + Collections.sort(edges); |
| 49 | + UnionFind uf = new UnionFind(vertices); |
| 50 | + List<Edge> mst = new ArrayList<>(); |
| 51 | + |
| 52 | + for (Edge edge : edges) { |
| 53 | + if (uf.union(edge.src, edge.dest)) { |
| 54 | + mst.add(edge); |
| 55 | + } |
| 56 | + if (mst.size() == vertices - 1) break; |
| 57 | + } |
| 58 | + |
| 59 | + return mst; |
| 60 | + } |
| 61 | + |
| 62 | + public static void main(String[] args) { |
| 63 | + int V = 4; |
| 64 | + List<Edge> edges = new ArrayList<>(); |
| 65 | + edges.add(new Edge(0, 1, 10)); |
| 66 | + edges.add(new Edge(0, 2, 6)); |
| 67 | + edges.add(new Edge(0, 3, 5)); |
| 68 | + edges.add(new Edge(1, 3, 15)); |
| 69 | + edges.add(new Edge(2, 3, 4)); |
| 70 | + |
| 71 | + List<Edge> mst = kruskalMST(edges, V); |
| 72 | + System.out.println("Edges in the Minimum Spanning Tree:"); |
| 73 | + for (Edge edge : mst) { |
| 74 | + System.out.println(edge.src + " - " + edge.dest + " : " + edge.weight); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments