From e385da26d9ea2936ef24a5e361c6d19596ad1247 Mon Sep 17 00:00:00 2001 From: Richa Kiran <64418209+richk21@users.noreply.github.com> Date: Wed, 1 Oct 2025 18:29:15 +0530 Subject: [PATCH] Implemented PrismAlgorithm --- .../thealgorithms/graph/PrismAlgorithm.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/main/java/com/thealgorithms/graph/PrismAlgorithm.java diff --git a/src/main/java/com/thealgorithms/graph/PrismAlgorithm.java b/src/main/java/com/thealgorithms/graph/PrismAlgorithm.java new file mode 100644 index 000000000000..584dfd6ee965 --- /dev/null +++ b/src/main/java/com/thealgorithms/graph/PrismAlgorithm.java @@ -0,0 +1,59 @@ +package com.thealgorithms.graph; + +import java.util.*; + + + +/** + * This class provides a method to compute the Minimum Spanning Tree (MST) + * weight using Prim's Algorithm without any custom helper class. + */ +public class PrismAlgorithm { + + /** + * Computes the total weight of the Minimum Spanning Tree (MST) + * for a given undirected, weighted graph using Prim's Algorithm. + * + * @param V Number of vertices in the graph. + * @param adj Adjacency list representation of the graph. + * Each entry: {adjacentNode, edgeWeight}. + * @return The sum of the edge weights in the MST. + * + *

Time Complexity: O(E log V)

+ *

Space Complexity: O(V + E)

+ */ + static int spanningTree(int V, ArrayList>> adj) { + + // Min-heap storing {weight, node} + PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); + + int[] visited = new int[V]; // visited array + int mstWeightSum = 0; + + // Start from node 0, with weight = 0 + pq.add(new int[]{0, 0}); + + while (!pq.isEmpty()) { + int[] current = pq.poll(); + int weight = current[0]; + int node = current[1]; + + if (visited[node] == 1) continue; + + visited[node] = 1; + mstWeightSum += weight; + + // Explore adjacent edges + for (ArrayList edge : adj.get(node)) { + int adjNode = edge.get(0); + int edgeWeight = edge.get(1); + + if (visited[adjNode] == 0) { + pq.add(new int[]{edgeWeight, adjNode}); + } + } + } + + return mstWeightSum; + } +}