Skip to content

Commit e385da2

Browse files
richk21shubham9345
authored andcommitted
Implemented PrismAlgorithm
1 parent 5e9d9f7 commit e385da2

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.thealgorithms.graph;
2+
3+
import java.util.*;
4+
5+
6+
7+
/**
8+
* This class provides a method to compute the Minimum Spanning Tree (MST)
9+
* weight using Prim's Algorithm without any custom helper class.
10+
*/
11+
public class PrismAlgorithm {
12+
13+
/**
14+
* Computes the total weight of the Minimum Spanning Tree (MST)
15+
* for a given undirected, weighted graph using Prim's Algorithm.
16+
*
17+
* @param V Number of vertices in the graph.
18+
* @param adj Adjacency list representation of the graph.
19+
* Each entry: {adjacentNode, edgeWeight}.
20+
* @return The sum of the edge weights in the MST.
21+
*
22+
* <p>Time Complexity: O(E log V)</p>
23+
* <p>Space Complexity: O(V + E)</p>
24+
*/
25+
static int spanningTree(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj) {
26+
27+
// Min-heap storing {weight, node}
28+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
29+
30+
int[] visited = new int[V]; // visited array
31+
int mstWeightSum = 0;
32+
33+
// Start from node 0, with weight = 0
34+
pq.add(new int[]{0, 0});
35+
36+
while (!pq.isEmpty()) {
37+
int[] current = pq.poll();
38+
int weight = current[0];
39+
int node = current[1];
40+
41+
if (visited[node] == 1) continue;
42+
43+
visited[node] = 1;
44+
mstWeightSum += weight;
45+
46+
// Explore adjacent edges
47+
for (ArrayList<Integer> edge : adj.get(node)) {
48+
int adjNode = edge.get(0);
49+
int edgeWeight = edge.get(1);
50+
51+
if (visited[adjNode] == 0) {
52+
pq.add(new int[]{edgeWeight, adjNode});
53+
}
54+
}
55+
}
56+
57+
return mstWeightSum;
58+
}
59+
}

0 commit comments

Comments
 (0)