ts实现图的最小生成树(普利姆算法)
prim.ts
import { pointSet, distance, Node, MAX, C } from "./utils";
/**
* 获取当前节点在pointSet中的index以获取在distance中的关联
* @param point 当前节点
* @returns 当前节点在pointSet中的index
*/
function getCurPointIndex(point: Node) {
return pointSet.indexOf(point);
}
/**
* 根据当前已经有的节点,来进行判断,获取到距离最短的点
* 获取代价最小的边
* @param pointSet 所有节点集合
* @param distance 距离集合
* @param nowPointSet 当前已经连接进去的节点集合
*/
function getMinDis(pointSet: Node[], distance: any[], nowPointSet: Node[]) {
let fromNode = null;
let minDisNode = null;
let minDis = MAX;
// 查看目前所有连接的点
for (let i = 0; i < nowPointSet.length; i++) {
// 获取当前节点在distance中的位置
const curDisSet = distance[getCurPointIndex(nowPointSet[i])];
// console.log("curDisSet", curDisSet);
for (let j = 0; j < curDisSet.length; j++) {
// console.log(curDisIndex[j]);
// 如果已经接入的点不包含这个点
// 而且这个点的距离是目前的最短距离
const curNode = pointSet[j];
if (!nowPointSet.includes(curNode) && curDisSet[j] < minDis) {
// 设置起点为当前节点
fromNode = nowPointSet[i];
// 设置距离最短的点
minDisNode = curNode;
minDis = curDisSet[j];
}
}
}
fromNode!.neighbor.push(minDisNode!);
minDisNode!.neighbor.push(fromNode!);
return minDisNode;
}
// 主要思想就是getMinDis函数
// 1. 检索传进去的每个nowPointSet,
// 在distance中找到对应的当前nowPointSet[i]的那一项,
// 找出不在nowPointSet中和距离最短的那个节点
function prim(pointSet: Node[], distance: any[], start: Node) {
// 保存已经进去的节点
const nowPointSet: Node[] = [];
nowPointSet.push(start);
// 获取代价最小的边
while (true) {
// console.log("nowPointSet", nowPointSet);
const minDisNode = getMinDis(pointSet, distance, nowPointSet);
nowPointSet.push(minDisNode!);
if (nowPointSet.length == pointSet.length) {
break;
}
}
}
prim(pointSet, distance, C);
console.log("pointSet", pointSet);
utils.ts
export const MAX = 1000000;
export class Node {
value: any;
neighbor: Node[];
constructor(value: any) {
this.value = value;
this.neighbor = [];
}
}
export const A = new Node("A");
export const B = new Node("B");
export const C = new Node("C");
export const D = new Node("D");
export const E = new Node("E");
// 字母的index对应distance的index
export const pointSet: Node[] = [A, B, C, D, E];
export const distance = [
[0, 4, 7, MAX, MAX],
[4, 0, 8, 6, MAX],
[7, 8, 0, 5, MAX],
[MAX, 6, 5, 0, 7],
[MAX, MAX, MAX, 7, 0],
];