项目作者: dranidis

项目描述 :
Kruskal's algorithm for a minimum spanning tree
高级语言: TypeScript
项目地址: git://github.com/dranidis/kruskal-mst.git
创建时间: 2021-03-15T20:56:46Z
项目社区:https://github.com/dranidis/kruskal-mst

开源协议:MIT License

下载


npm version
Build Status
Coverage Status
Dependencies Status

kruskal-mst

Kruskal’s algorithm finds a minimum spanning forest of an undirected edge-weighted graph. If the graph is connected, it finds a minimum spanning tree.

For more information read: https://en.wikipedia.org/wiki/Kruskal%27s_algorithm

Usage

Javascript

  1. k = require('kruskal-mst');
  2. edges = [
  3. { from: 'A', to: 'B', weight: 1 },
  4. { from: 'A', to: 'C', weight: 5 },
  5. { from: 'A', to: 'E', weight: 7 },
  6. { from: 'B', to: 'C', weight: 2 },
  7. { from: 'B', to: 'D', weight: 5 },
  8. { from: 'C', to: 'F', weight: 8 },
  9. { from: 'D', to: 'E', weight: 3 },
  10. { from: 'D', to: 'F', weight: 4 },
  11. { from: 'E', to: 'F', weight: 5 },
  12. ];
  13. mst = k.kruskal(edges);
  14. console.log(mst);

Output:

  1. [
  2. { from: 'A', to: 'B', weight: 1 },
  3. { from: 'B', to: 'C', weight: 2 },
  4. { from: 'D', to: 'E', weight: 3 },
  5. { from: 'D', to: 'F', weight: 4 },
  6. { from: 'B', to: 'D', weight: 5 }
  7. ]

Typescript

  1. import { kruskal, Edge } from 'kruskal-mst';
  2. const edges: Edge<string>[] = [
  3. { from: 'A', to: 'B', weight: 1 },
  4. { from: 'A', to: 'C', weight: 5 },
  5. { from: 'A', to: 'E', weight: 7 },
  6. { from: 'B', to: 'C', weight: 2 },
  7. { from: 'B', to: 'D', weight: 5 },
  8. { from: 'C', to: 'F', weight: 8 },
  9. { from: 'D', to: 'E', weight: 3 },
  10. { from: 'D', to: 'F', weight: 4 },
  11. { from: 'E', to: 'F', weight: 5 },
  12. ];
  13. const spanningTree = kruskal(edges);
  14. console.log(spanningTree);