class Graph {
nodes: string[];
edges: Map<string, Map<string, number>>;
constructor(nodes: string[]) {
this.nodes = nodes;
this.edges = new Map();
for (const node of nodes) {
this.edges.set(node, new Map());
}
}
addEdge(u: string, v: string, weight: number) {
this.edges.get(u)?.set(v, weight);
this.edges.get(v)?.set(u, weight);
}
}
function primMST(graph: Graph, start: string): [string, string, number][] {
const mstEdges: [string, string, number][] = [];
const visited = new Set<string>();
const minHeap: {node: string; from: string | null; weight: number}[] = [];
// Add start node edges to heap
visited.add(start);
for (const [neighbor, weight] of graph.edges.get(start)!) {
minHeap.push({node: neighbor, from: start, weight});
}
// Helper to get smallest edge
function extractMin() {
let minIndex = 0;
for (let i = 1; i < minHeap.length; i++) {
if (minHeap[i].weight < minHeap[minIndex].weight) {
minIndex = i;
}
}
return minHeap.splice(minIndex, 1)[0];
}
while (minHeap.length > 0 && visited.size < graph.nodes.length) {
const {node, from, weight} = extractMin();
if (visited.has(node)) continue; // skip if already in MST
visited.add(node);
mstEdges.push([from!, node, weight]);
// Add new edges from this node
for (const [neighbor, w] of graph.edges.get(node)!) {
if (!visited.has(neighbor)) {
minHeap.push({node: neighbor, from: node, weight: w});
}
}
}
return mstEdges;
}
// Driver code
const graph = new Graph(['A', 'B', 'C']);
graph.addEdge('A', 'B', 5);
graph.addEdge('A', 'C', 3);
graph.addEdge('B', 'C', 4);
const mst = primMST(graph, 'A');
let totalCost = 0;
for (const [from, to, weight] of mst) {
console.log(`${from} - ${to}: ${weight}`);
totalCost += weight;
}
console.log(`Total cost: ${totalCost}`);Mark start node as included in MST
for (const [neighbor, weight] of graph.edges.get(start)!) { minHeap.push({node: neighbor, from: start, weight}); }
Add all edges from start node to candidate edges
const {node, from, weight} = extractMin();
Select edge with smallest weight connecting MST to new node
if (visited.has(node)) continue;
Skip nodes already included to avoid cycles
visited.add(node); mstEdges.push([from!, node, weight]);
Add new node and edge to MST
for (const [neighbor, w] of graph.edges.get(node)!) { if (!visited.has(neighbor)) { minHeap.push({node: neighbor, from: node, weight: w}); } }
Add new edges from recently added node to candidates
A - C: 3
C - B: 4
Total cost: 7