diff --git a/src/main/java/com/thealgorithms/graph/PrimAlgorithm.java b/src/main/java/com/thealgorithms/graph/PrimAlgorithm.java new file mode 100644 index 000000000000..fe7a70a51a4f --- /dev/null +++ b/src/main/java/com/thealgorithms/graph/PrimAlgorithm.java @@ -0,0 +1,83 @@ +package com.thealgorithms.graph; + +import java.util.ArrayList; +import java.util.PriorityQueue; + +/** + * This class provides a method to compute the weight of the + * Minimum Spanning Tree (MST) of a graph using Prim's Algorithm. + */ +public final class PrimAlgorithm { + + private PrimAlgorithm() { + throw new UnsupportedOperationException("Utility class"); + } + + /** + * Helper record representing an edge with its associated weight and node. + * + * @param node the target node connected by the edge + * @param weight the weight of the edge + */ + private record Pair(int node, int weight) { + } + + /** + * Computes the total weight of the Minimum Spanning Tree (MST) + * for a given undirected, weighted graph. + * + *
The algorithm uses a PriorityQueue (min-heap) to always pick + * the edge with the smallest weight that connects a new vertex to + * the growing MST. It ensures that no cycles are formed.
+ * + * @param V number of vertices in the graph + * @param adj adjacency list representation of the graph + * for each node, the adjacency list contains a list of + * {adjacentNode, edgeWeight} + * @return the sum of the edge weights in the MST + * + *Time Complexity: O(E log V), where E is the number of edges + * and V is the number of vertices.
+ *Space Complexity: O(V + E) due to adjacency list and visited array.
+ */ + public static int spanningTree(int V, ArrayList