Skip to content

KRUSKAL Algorithm โ€‹

๊ฐ„์„ ์„ ํ•˜๋‚˜์”ฉ ์„ ํƒํ•˜์—ฌ MST๋ฅผ ์ฐพ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

  1. ๋ชจ๋“  ๊ฐ„์„ ์˜ ๊ฐ€์ค‘์น˜์—๋”ฐ๋ผ ์ •๋ ฌ
  2. ๊ฐ€์ค‘์น˜๊ฐ€ ๊ฐ€์žฅ ๋‚ฎ์€ ๊ฐ„์„ ๋ถ€ํ„ฐ ์„ ํƒํ•˜๋ฉฐ ๊ทธ๋ž˜ํ”„๋ฅผ ๊ทธ๋ ค๋‚˜๊ฐ
    • ์‚ฌ์ดํด์ด ์กด์žฌํ•˜์ง€ ์•Š๋„๋ก ๊ฐ„์„ ์„ ์„ ํƒํ•ด์•ผํ•จ.
  3. N-1๊ฐœ์˜ ๊ฐ„์„ ์ด ์„ ํƒ๋  ๋•Œ๊นŒ์ง€ (2)๋ฅผ ๋ฐ˜๋ณต

kruskal

javascript
// ์ฃผ์–ด์ง„ ๊ทธ๋ž˜ํ”„ [a,b,c,d,e,f,g]
const edgeCnt = 9;
const graph = [
    [0,7,0,5,0,0,0],
    [7,0,8,9,7,0,0],
    [0,8,0,0,5,0,0],
    [5,9,0,0,15,6,0],
    [0,7,5,15,0,8,9],
    [0,0,0,6,8,0,11],
    [0,0,0,0,9,11,0]
]
class Edge {
    constructor(from, to, cost) {
        this.from = from;
        this.to = to;
        this.cost = cost;
    }
}

let arr = graph.map((item,from) => item.map((cost, to) => new Edge(from, to, cost)).filter(edge => edge.cost))
let queue = [];
const priorityCost = (a,b) => b.cost - a.cost

const makeSet = (p,x) => p[x] = x
const findSet = (p,x) => {
    if(p[x] === x) return x;
    return p[x] = findSet(p,p[x]);
}
const unionSet = (p,edge) => {
    let pFrom = findSet(p, edge.from);
    let pTo = findSet(p, edge.to);

    if(pFrom !== pTo) {
        p[pTo] = pFrom;
        return true;
    }
    return false;
}


const kruskal = () => {
    let minimunCost = 0;      // ์ตœ์†Œ๋น„์šฉ
    const edgeNumber = 7;     // ์ •์ ์˜ ๊ฐœ์ˆ˜
    let lineCnt = edgeNumber-1;    // ์ตœ์†Œ๋น„์šฉ์˜ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜

    // ์ •์ ์˜ ๊ฐœ์ˆ˜๋งŒํผ ์ง‘ํ•ฉ์ƒ์„ฑ
    let p = Array(edgeNumber);        
    for(let i = 0 ; i < edgeNumber; i++) makeSet(p,i);

    arr = arr.flat().sort(priorityCost);

    while(arr.length && lineCnt) {
        const edge = arr.pop();
        if(unionSet(p,edge,minimunCost)) {
            minimunCost += edge.cost;
            lineCnt--;
            console.log(`minimum cost : ${minimunCost}, edge : `, edge)
        }
    }
}
kruskal();
// console
/*
    minimum cost : 5, edge :  Edge { from: 4, to: 2, cost: 5 }
    minimum cost : 10, edge :  Edge { from: 3, to: 0, cost: 5 }
    minimum cost : 16, edge :  Edge { from: 5, to: 3, cost: 6 }
    minimum cost : 23, edge :  Edge { from: 4, to: 1, cost: 7 }
    minimum cost : 30, edge :  Edge { from: 1, to: 0, cost: 7 }
    minimum cost : 39, edge :  Edge { from: 6, to: 4, cost: 9 }
*/