function primsMST(V, adj) {
const visited = new Array(V).fill(false);
const minHeap = [[0, 0]]; // [weight, vertex]
const mstEdges = [];
let totalWeight = 0;
while (minHeap.length) {
minHeap.sort((a, b) => a[0] - b[0]);
const [weight, u] = minHeap.shift();
if (visited[u]) continue;
visited[u] = true;
totalWeight += weight;
for (const [v, wt] of adj[u]) {
if (!visited[v]) {
minHeap.push([wt, v]);
mstEdges.push([u, v]);
}
}
}
console.log("MST Weight:", totalWeight);
return { totalWeight, mstEdges };
}
// Example usage
const V = 5;
const adj = [
[[1,2], [3,6]],
[[0,2], [2,3], [3,8], [4,5]],
[[1,3], [4,7]],
[[0,6], [1,8], [4,9]],
[[1,5], [2,7], [3,9]]
];
console.log(primsMST(V, adj));