Kruskal’s Algorithm


  • ElogE, E+V

    function kruskalsAlgorithm(edges) {
    // create arr to store edge
    const weightEdges = ();
    for (let i = 0; i < edges.length; i++) {
      const here = i;
      for (const (there, weight) of edges(here)) {
        weightEdges.push((here, there, weight));
      }
    }
    
    // sort arr asc depending on edge weight
    weightEdges.sort((a, b) => a(2) - b(2));
    
    // crate union find
    const uf = new UnionFind(edges.length);
    // create mst to find 
    const mst = edges.map(a => ());
    for (let i = 0; i < weightEdges.length; i++) {
      const (here, there, weight) = weightEdges(i);
      if (uf.find(here) === uf.find(there)) continue;
      mst(here).push((there, weight));
      mst(there).push((here, weight));
      uf.union(here, there);
    }
    
    return mst;
    }
    
    

클래스 UnionFind {
생성자(크기) {
this.arr = 새 배열(크기);
for (let i = 0; i < 크기; i++) {
this.arr(i) = I;
}
this.weights = new Array(크기).fill(0);
}

생성) {
return this.arr(a) = a;
}

찾기(값) {
if (값 === 정의되지 않음)
null을 반환합니다.

if (this.arr(value) === value)
  return value;

return this.arr(value) = this.find(this.arr(value));

}

합집합(a,b) {
const rootA = this.find(a);
const rootB = this.find(b);
if (rootA === rootB) 반환;

if (this.weights(rootA) > this.weights(rootB)) {
  this.arr(rootB) = rootA;
  this.weights(rootA)++;
} else {
  this.arr(rootA) = rootB;
  this.weights(rootB)++;
}

return;

}

}

// 다음 줄을 편집하지 마십시오.
exports.kruskalsAlgorithm = kruskalsAlgorithm;

“`