| 12 | * @see https://en.wikipedia.org/wiki/Kruskal%27s_algorithm |
| 13 | */ |
| 14 | export const kruskal = ( |
| 15 | edges: Edge[], |
| 16 | num_vertices: number |
| 17 | ): [Edge[], number] => { |
| 18 | let cost = 0 |
| 19 | const minimum_spanning_tree = [] |
| 20 | |
| 21 | // Use a disjoint set to quickly join sets and find if vertices live in different sets |
| 22 | const sets = new DisjointSet(num_vertices) |
| 23 | |
| 24 | // Sort the edges in ascending order by weight so that we can greedily add cheaper edges to the tree |
| 25 | edges.sort((a, b) => a.weight - b.weight) |
| 26 | |
| 27 | for (const edge of edges) { |
| 28 | if (sets.find(edge.a) !== sets.find(edge.b)) { |
| 29 | // Node A and B live in different sets. Add edge(a, b) to the tree and join the nodes' sets together. |
| 30 | minimum_spanning_tree.push(edge) |
| 31 | cost += edge.weight |
| 32 | sets.join(edge.a, edge.b) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | return [minimum_spanning_tree, cost] |
| 37 | } |
| 38 | |
| 39 | export class Edge { |
| 40 | a: number = 0 |