Skip to content

Commit dbfc996

Browse files
committed
Updated PrismAlgorithm-III
1 parent dd01551 commit dbfc996

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

src/main/java/com/thealgorithms/graph/PrimAlgorithm.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.thealgorithms.graph;
22

33
import java.util.ArrayList;
4+
import java.util.Comparator;
45
import java.util.PriorityQueue;
56

67
/**
@@ -26,26 +27,22 @@ private record Pair(int node, int weight) {
2627
* Computes the total weight of the Minimum Spanning Tree (MST)
2728
* for a given undirected, weighted graph.
2829
*
29-
* <p>The algorithm uses a PriorityQueue (min-heap) to always pick
30-
* the edge with the smallest weight that connects a new vertex to
31-
* the growing MST. It ensures that no cycles are formed.</p>
32-
*
33-
* @param V number of vertices in the graph
34-
* @param adj adjacency list representation of the graph
35-
* for each node, the adjacency list contains a list of
36-
* {adjacentNode, edgeWeight}
30+
* @param vertices number of vertices in the graph
31+
* @param adj adjacency list representation of the graph
32+
* for each node, the adjacency list contains a list of
33+
* {adjacentNode, edgeWeight}
3734
* @return the sum of the edge weights in the MST
3835
*
3936
* <p>Time Complexity: O(E log V), where E is the number of edges
4037
* and V is the number of vertices.</p>
4138
* <p>Space Complexity: O(V + E) due to adjacency list and visited array.</p>
4239
*/
43-
public static int spanningTree(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj) {
40+
public static int spanningTree(int vertices, ArrayList<ArrayList<ArrayList<Integer>>> adj) {
4441
// Min-heap to pick edge with the smallest weight
45-
PriorityQueue<Pair> pq = new PriorityQueue<>((x, y) -> x.weight - y.weight);
42+
PriorityQueue<Pair> pq = new PriorityQueue<>(Comparator.comparingInt(Pair::weight));
4643

4744
// Array to keep track of visited vertices
48-
boolean[] visited = new boolean[V];
45+
boolean[] visited = new boolean[vertices];
4946

5047
// Start with node 0 (arbitrary choice), with edge weight = 0
5148
pq.add(new Pair(0, 0));

0 commit comments

Comments
 (0)