From ebf707276bc91fef8c184ee1ebf31c6fd67c6106 Mon Sep 17 00:00:00 2001 From: Yuri Tatishchev Date: Tue, 29 Apr 2025 18:12:43 -0700 Subject: [PATCH] Assignment 10: mst solve --- 10-labMST/Assignment.java | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/10-labMST/Assignment.java b/10-labMST/Assignment.java index f465019..b204674 100644 --- a/10-labMST/Assignment.java +++ b/10-labMST/Assignment.java @@ -71,7 +71,42 @@ public class Assignment { // of every vertex in the resulting tree. Other fields of QNode are optional // but may be useful in your implementation. public static List Prim(Graph g) { - return new ArrayList(Collections.nCopies(g.getLength(), new QNode())); + // Initialize the QNode list + List qNodes = new ArrayList<>(g.getLength()); + for (int i = 0; i < g.getLength(); i++) { + qNodes.add(new QNode()); + qNodes.get(i).id = i; + // Set key to max value for lowest priority + qNodes.get(i).key = Integer.MAX_VALUE; + } + + // Start from the first vertex + qNodes.get(0).key = 0; + + // Priority queue to select the vertex with the minimum key as the next to be added to the MST + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(qNode -> qNode.key)); + // Add the first vertex to the priority queue + pq.add(qNodes.get(0)); + + while (!pq.isEmpty()) { + // Get the vertex with the minimum key + QNode u = pq.poll(); + // Mark it as part of the MST + u.isValid = false; + + // For each adjacent vertex, + // if it is not already in the MST and the weight is less than the current key + // update the key and parent (pi) + for (int v : g.getAdjacent(u.id)) { + if (qNodes.get(v).isValid && g.getWeight(u.id, v) < qNodes.get(v).key) { + qNodes.get(v).key = g.getWeight(u.id, v); + qNodes.get(v).pi = u.id; + pq.add(qNodes.get(v)); + } + } + } + + return qNodes; } public static void run(String inputPath) {