Skip to content

Commit e61fafa

Browse files
committed
Updated PrismAlgorithm-IV
1 parent dbfc996 commit e61fafa

1 file changed

Lines changed: 9 additions & 9 deletions

File tree

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

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

3-
import java.util.ArrayList;
4-
import java.util.Comparator;
3+
import java.util.List;
54
import java.util.PriorityQueue;
5+
import java.util.Comparator;
66

77
/**
88
* This class provides a method to compute the weight of the
@@ -20,24 +20,23 @@ private PrimAlgorithm() {
2020
* @param node the target node connected by the edge
2121
* @param weight the weight of the edge
2222
*/
23-
private record Pair(int node, int weight) {
24-
}
23+
private record Pair(int node, int weight) {}
2524

2625
/**
2726
* Computes the total weight of the Minimum Spanning Tree (MST)
2827
* for a given undirected, weighted graph.
2928
*
3029
* @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}
30+
* @param adj adjacency list representation of the graph
31+
* for each node, the adjacency list contains a list of
32+
* {adjacentNode, edgeWeight}
3433
* @return the sum of the edge weights in the MST
3534
*
3635
* <p>Time Complexity: O(E log V), where E is the number of edges
3736
* and V is the number of vertices.</p>
3837
* <p>Space Complexity: O(V + E) due to adjacency list and visited array.</p>
3938
*/
40-
public static int spanningTree(int vertices, ArrayList<ArrayList<ArrayList<Integer>>> adj) {
39+
public static int spanningTree(int vertices, List<? extends List<? extends List<Integer>>> adj) {
4140
// Min-heap to pick edge with the smallest weight
4241
PriorityQueue<Pair> pq = new PriorityQueue<>(Comparator.comparingInt(Pair::weight));
4342

@@ -65,10 +64,11 @@ public static int spanningTree(int vertices, ArrayList<ArrayList<ArrayList<Integ
6564
mstWeightSum += weight;
6665

6766
// Traverse all adjacent edges
68-
for (ArrayList<Integer> edge : adj.get(node)) {
67+
for (List<Integer> edge : adj.get(node)) {
6968
int adjNode = edge.get(0);
7069
int edgeWeight = edge.get(1);
7170

71+
// Only consider unvisited nodes
7272
if (!visited[adjNode]) {
7373
pq.add(new Pair(adjNode, edgeWeight));
7474
}

0 commit comments

Comments
 (0)