1.kruskal算法
const INF = Number.MAX_SAFE_INTEGER; const find = (i, parent) => { while (parent[i]) { i = parent[i]; // eslint-disable-line prefer-destructuring } return i; }; const union = (i, j, parent) => { if (i !== j) { parent[j] = i; return true; } return false; }; const initializeCost = graph => { const cost = []; const { length } = graph; for (let i = 0; i < length; i++) { cost[i] = []; for (let j = 0; j < length; j++) { if (graph[i][j] === 0) { cost[i][j] = INF; } else { cost[i][j] = graph[i][j]; } } } return cost; }; export const kruskal = graph => { const { length } = graph; const parent = []; let ne = 0; let a; let b; let u; let v; const cost = initializeCost(graph); while (ne < length - 1) { for (let i = 0, min = INF; i < length; i++) { for (let j = 0; j < length; j++) { if (cost[i][j] < min) { min = cost[i][j]; a = u = i; b = v = j; } } } u = find(u, parent); v = find(v, parent); if (union(u, v, parent)) { ne++; } cost[a][b] = cost[b][a] = INF; } return parent; };
2.prim算法
var graph = [ [0, 2, 4, 0, 0, 0], [2, 0, 2, 4, 2, 0], [4, 2, 0, 0, 3, 0], [0, 4, 0, 0, 3, 2], [0, 2, 3, 3, 0, 2], [0, 0, 0, 2, 2, 0] ] function prime(graph,src){ const dist = []; const visited = []; const parent = []; const {length} = graph; const INF = Number.MAX_SAFE_INTEGER; for(let i = 0; i < length; i++){ dist[i] = INF; visited[i] = false; } dist[src] = 0; parent[src] = -1; let index = 0; while(index < length-1){ let currentEdge = graph[src]; visited[src] = true; for(let i = 0; i <currentEdge.length; i++){ if(currentEdge[i]!==0){ if(currentEdge[i]<dist[i]){ dist[i] = currentEdge[i]; parent[i] = src; } } } let min = INF; let minIndex = -1; for(let i = 0; i < dist.length; i++){ if(!visited[i] && dist[i] < min){ min = dist[i]; minIndex = i; } } src = minIndex; index++; } return parent; } console.log(prime(graph,0));