11package com .thealgorithms .graph ;
22
33import java .util .ArrayList ;
4+ import java .util .Comparator ;
45import 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