Prime Algorithm β
νλμ μ μ μμ μ°κ²°λ κ°μ λ€ μ€μ νλμ© μ ννλ©΄μ MSTλ₯Ό λ§λ€μ΄ κ°λ λ°©μ
- μμ μ μ μ νλ μ νν΄μ μμ
- μ νν μ μ κ³Ό μΈμ νλ μ μ λ€ μ€μ μ΅μ λΉμ©μ κ°μ μ΄ μ‘΄μ¬νλ μ μ μ μ ν
- κ°μ λ€μ 보κ΄νλ
μ°μ μμ ν<κ°μ >
λ₯Ό μ΄μ©νμ¬ κ°μ₯ μμ κ°μ€μΉμ κ°μ λ½λλ€. - μ κ°μ μμ
μ¬μ΄ν΄μ΄ μ‘΄μ¬νμ§ μλλ‘
μ μ μ λ°©λ¬Έμ²λ¦¬λ₯Ό νλ€.
- κ°μ λ€μ 보κ΄νλ
- λͺ¨λ μ μ μ΄ μ νλ λκΉμ§ (1),(2) κ³Όμ μ λ°λ³΅
javascript
// μ£Όμ΄μ§ κ·Έλν [a,b,c,d,e,f,g,h,i]
const edgeCnt = 9
const graph = [
[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 0, 6, 7],
]
class Edge {
constructor(next, cost) {
this.next = next
this.cost = cost
}
}
let arr = graph.map((item) => item.map((cost, next) => new Edge(next, cost)).filter((edge) => edge.cost))
let visited = Array(9).fill(false)
let pq = []
const priorityCost = (a, b) => b.cost - a.cost
const prim = (start = 0) => {
let minimunCost = 0 // μ΅μλΉμ©
let lineCnt = edgeCnt - 1 // μ΅μ κ°μ μ μ
visited[start] = true // μ΄κΈ° λ
Έλμ λ°©λ¬Έ μ²λ¦¬
// μ΄κΈ° λ
Έλμ κ°μ μ 보λ₯Ό λͺ¨λ PriorityQueueμ λ£μ΄μ€λ€.
arr[start].forEach((edge) => pq.push(edge))
pq.sort(priorityCost)
// κ°μ λ€μ λΉκ΅
while (pq.length && lineCnt) {
const e = pq.pop()
if (visited[e.next]) continue
visited[e.next] = true
minimunCost += e.cost
lineCnt--
arr[e.next].filter((edge) => !visited[edge.next]).forEach((edge) => pq.push(edge)) // λ°©λ¬Έλ λ
Έλμ λν κ°μ μ λ£μ΄μ£Όμ§ μμ.
pq.sort(priorityCost)
}
return minimunCost
}
console.log(prim()) // 37