image.png
如上图

普利姆算法(加点法)

1:任选一个点作为起点
2:找到以当前选中点为起点路径最短的边
3:如果这个边的另一端没有被连通进来,那就连接
4:如果这个边的另一端也早就连进来,则看倒数第二短的边
5:重复2-4的步骤直到将所有的点都连通为止
当起始点为C时连接步骤为
C->D->B->A->E
用代码实现为
其上图中路线的图的关系为
image.png
就可以是用二维数组表示图的关系

  1. let max = 999999;
  2. let pointSet = []; //储存点
  3. let distance = [
  4. [0, 4, 7, max, max],
  5. [4, 0, 8, 6, max],
  6. [7, 8, 0, 5, max],
  7. [max, 6, 5, 0, 7],
  8. [max, max, max, 7, 0]
  9. ] // 将图的信息储存下来
  10. class Node {
  11. constructor(value) {
  12. this.value = value;
  13. this.neighbor = [];
  14. }
  15. }
  16. let a = new Node('A');
  17. let b = new Node('B');
  18. let c = new Node('C');
  19. let d = new Node('D');
  20. let e = new Node('E');
  21. pointSet.push(a)
  22. pointSet.push(b)
  23. pointSet.push(c)
  24. pointSet.push(d)
  25. pointSet.push(e)
  26. /**
  27. *获取点的索引
  28. * @param {*} str 点
  29. * @returns 返回点的索引值
  30. */
  31. function getIndex(str) {
  32. for (let i = 0; i < pointSet.length; i++) {
  33. if (pointSet[i].value == str) {
  34. return i;
  35. }
  36. }
  37. return -1;
  38. }
  39. /**
  40. * 获取距离最短的点
  41. * @param {*} pointSet 点的集合
  42. * @param {*} distance 线的集合
  43. * @param {*} nowPointSet 已连接点的集合
  44. */
  45. function getMinDisNode(pointSet, distance, nowPointSet) {
  46. let min = max; // 最大值
  47. let startNode = null; //开始节点
  48. let endNode = null; // 结束节点
  49. for (let i = 0; i < nowPointSet.length; i++) {
  50. let index = getIndex(nowPointSet[i].value)
  51. for (let j = 0; j < distance[index].length; j++) {
  52. let thisNode = pointSet[j]
  53. let thisValue = distance[index][j]
  54. //满足不能有重复点,且距离最短
  55. if (nowPointSet.indexOf(thisNode) < 0 && thisValue < min) {
  56. min = thisValue;
  57. startNode = nowPointSet[i];
  58. endNode = thisNode;
  59. }
  60. }
  61. }
  62. startNode.neighbor.push(endNode)
  63. endNode.neighbor.push(startNode)
  64. return endNode
  65. }
  66. function prim(pointSet, distance, start) {
  67. let nowPointSet = [];
  68. nowPointSet.push(start);
  69. while (true) {
  70. let endNode = getMinDisNode(pointSet, distance, nowPointSet)
  71. nowPointSet.push(endNode)
  72. if (nowPointSet.length == pointSet.length) {
  73. break;
  74. }
  75. }
  76. }
  77. prim(pointSet, distance, pointSet[2])
  78. console.log(pointSet)