Assignment 10: mst solve

This commit is contained in:
Yuri Tatishchev 2025-04-29 18:12:43 -07:00
parent 92803f6bc5
commit ebf707276b
Signed by: CaZzzer
SSH Key Fingerprint: SHA256:sqXB3fe0LMpfH+IeM/vlmxKdso52kssrIJBlwKXVe1U

View File

@ -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<QNode> Prim(Graph g) {
return new ArrayList<QNode>(Collections.nCopies(g.getLength(), new QNode()));
// Initialize the QNode list
List<QNode> 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<QNode> 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) {