export default function prims( list: WeightedAdjacencyList, ): WeightedAdjacencyList | null { const n = list.length; if (n === 0) { return null; } const inMST = new Array(n).fill(false); const mst: WeightedAdjacencyList = Array.from({ length: n }, () => []); const minEdge: { to: number; from: number; weight: number }[] = new Array( n, ).fill(null as any); minEdge[0] = { to: 0, from: -1, weight: 0 }; for (let i = 0; i < n; i++) { let u = -1; for (let v = 0; v < n; v++) { if ( !inMST[v] && (u === -1 || (minEdge[v] && minEdge[v].weight < minEdge[u].weight)) ) { u = v; } } if (u === -1 || minEdge[u] === null) { return null; } inMST[u] = true; const edge = minEdge[u]; if (edge.from !== -1) { mst[edge.from].push({ to: u, weight: edge.weight }); mst[u].push({ to: edge.from, weight: edge.weight }); } for (const neighbor of list[u]) { if ( !inMST[neighbor.to] && (!minEdge[neighbor.to] || neighbor.weight < minEdge[neighbor.to].weight) ) { minEdge[neighbor.to] = { to: neighbor.to, from: u, weight: neighbor.weight, }; } } } return mst; }