以下是使用 Kruskal 算法求解最小连通图的 JavaScript 代码:

function find(parent, i) {
    if (parent[i] === i) {
        return i;
    }
    return find(parent, parent[i]);
}

function union(parent, rank, x, y) {
    let xroot = find(parent, x);
    let yroot = find(parent, y);

    if (rank[xroot] < rank[yroot]) {
        parent[xroot] = yroot;
    } else if (rank[xroot] > rank[yroot]) {
        parent[yroot] = xroot;
    } else {
        parent[yroot] = xroot;
        rank[xroot]++;
    }
}

function kruskalMST(graph) {
    let result = [];
    let i = 0;
    let e = 0;

    graph.sort((a, b) => a.weight - b.weight);

    let parent = [];
    let rank = [];

    for (let j = 0; j < graph.length; j++) {
        parent[j] = j;
        rank[j] = 0;
    }

    while (e < graph.length - 1) {
        let nextEdge = graph[i++];
        let x = find(parent, nextEdge.src);
        let y = find(parent, nextEdge.dest);

        if (x !== y) {
            result.push(nextEdge);
            union(parent, rank, x, y);
            e++;
        }
    }

    return result;
}

let graph = [
    { src: 0, dest: 1, weight: 10 },
    { src: 0, dest: 2, weight: 6 },
    { src: 0, dest: 3, weight: 5 },
    { src: 1, dest: 3, weight: 15 },
    { src: 2, dest: 3, weight: 4 }
];

let mst = kruskalMST(graph);

console.log(mst);

注:上述代码中的 graph 数组表示的是一个边的数组,其中每个元素都包含 srcdestweight 属性,分别表示边的起点、终点和权重。

JS求最小连通图 给我代码

原文地址: https://www.cveoy.top/t/topic/bbmK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录