|
| 1 | +package com.thealgorithms.graph; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * Implementation of Kruskal's Algorithm to find |
| 9 | + * the Minimum Spanning Tree (MST) of a connected, |
| 10 | + * undirected, weighted graph. |
| 11 | + */ |
| 12 | +public final class KruskalMST { |
| 13 | + |
| 14 | + private KruskalMST() { |
| 15 | + // Utility class |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * Finds the Minimum Spanning Tree using Kruskal's Algorithm. |
| 20 | + * |
| 21 | + * @param vertices number of vertices in the graph |
| 22 | + * @param edges list of all edges in the graph |
| 23 | + * @return list of edges forming the MST |
| 24 | + * @throws IllegalArgumentException if vertices <= 0 |
| 25 | + */ |
| 26 | + public static List<Edge> findMST(final int vertices, final List<Edge> edges) { |
| 27 | + if (vertices <= 0) { |
| 28 | + throw new IllegalArgumentException("Number of vertices must be positive"); |
| 29 | + } |
| 30 | + |
| 31 | + final List<Edge> mst = new ArrayList<>(); |
| 32 | + final DisjointSetUnion dsu = new DisjointSetUnion(vertices); |
| 33 | + |
| 34 | + Collections.sort(edges); |
| 35 | + |
| 36 | + for (final Edge edge : edges) { |
| 37 | + final int rootU = dsu.find(edge.source); |
| 38 | + final int rootV = dsu.find(edge.destination); |
| 39 | + |
| 40 | + if (rootU != rootV) { |
| 41 | + mst.add(edge); |
| 42 | + dsu.union(rootU, rootV); |
| 43 | + |
| 44 | + if (mst.size() == vertices - 1) { |
| 45 | + break; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return mst; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Disjoint Set Union (Union-Find) with |
| 55 | + * path compression and union by rank. |
| 56 | + */ |
| 57 | + private static final class DisjointSetUnion { |
| 58 | + |
| 59 | + private final int[] parent; |
| 60 | + private final int[] rank; |
| 61 | + |
| 62 | + private DisjointSetUnion(final int size) { |
| 63 | + parent = new int[size]; |
| 64 | + rank = new int[size]; |
| 65 | + |
| 66 | + for (int i = 0; i < size; i++) { |
| 67 | + parent[i] = i; |
| 68 | + rank[i] = 0; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private int find(final int node) { |
| 73 | + if (parent[node] != node) { |
| 74 | + parent[node] = find(parent[node]); |
| 75 | + } |
| 76 | + return parent[node]; |
| 77 | + } |
| 78 | + |
| 79 | + private void union(final int u, final int v) { |
| 80 | + if (rank[u] < rank[v]) { |
| 81 | + parent[u] = v; |
| 82 | + } else if (rank[u] > rank[v]) { |
| 83 | + parent[v] = u; |
| 84 | + } else { |
| 85 | + parent[v] = u; |
| 86 | + rank[u]++; |
| 87 | + } |
| 88 | + } |
| 89 | + } |
| 90 | +} |
0 commit comments