Skip to content

Prime Algorithm ​

ν•˜λ‚˜μ˜ μ •μ μ—μ„œ μ—°κ²°λœ κ°„μ„ λ“€ 쀑에 ν•˜λ‚˜μ”© μ„ νƒν•˜λ©΄μ„œ MSTλ₯Ό λ§Œλ“€μ–΄ κ°€λŠ” 방식

  1. μž„μ˜ 정점을 ν•˜λ‚˜ μ„ νƒν•΄μ„œ μ‹œμž‘
  2. μ„ νƒν•œ 정점과 μΈμ ‘ν•˜λŠ” 정점듀 μ€‘μ˜ μ΅œμ†Œ λΉ„μš©μ˜ 간선이 μ‘΄μž¬ν•˜λŠ” 정점을 선택
    • 간선듀을 λ³΄κ΄€ν•˜λŠ” μš°μ„ μˆœμœ„ 큐<κ°„μ„ >λ₯Ό μ΄μš©ν•˜μ—¬ κ°€μž₯ μž‘μ€ κ°€μ€‘μΉ˜μ˜ 값을 λ½‘λŠ”λ‹€.
    • μœ„ κ°€μ •μ—μ„œ 사이클이 μ‘΄μž¬ν•˜μ§€ μ•Šλ„λ‘ μ •μ μ˜ 방문처리λ₯Ό ν•œλ‹€.
  3. λͺ¨λ“  정점이 선택될 λ•ŒκΉŒμ§€ (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