Prim’s Algorithm

  • linear

let ans;
let visited;

function primsAlgorithm(edges) {
  ans = [];
  visited = new Array(edges.length).fill(0);

  for (let vertex = 0; vertex < edges.length; vertex++) {
    if (visited[vertex] !== 0) continue;
    findMst(edges, vertex);
  }
  
  return ans;
}

function findMinIdx(arr) {
  let min = Infinity;
  let idx = 0;

  for (let i = 0; i < arr.length; i++) {
    const [w, here, there] = arr[i];
    if (min > w) {
      min = w;
      idx = i;
    }
  }

  return idx;
  
}

function findMst(adjs, vertex) {
  const arr = [];

  const adj = adjs[vertex];
  for (const [there, w] of adj) {
    arr.push([w, vertex, there]);
  }
  visited[vertex] = 1;

  while (arr.length > 0) {
    const  minIdx = findMinIdx(arr);
    const [w, here, there] = arr.splice(minIdx, 1)[0];
    
    if (visited[there] !== 0) continue;

    ans[here] = ans[here] ?? [];
    ans[here].push([there, w]);
    
    ans[there] = ans[there] ?? [];
    ans[there].push([here, w]);

    for (const [next, w] of adjs[there] || []) {
      if (visited[next] !== 0) continue;
      arr.push([w, there, next]);
    }

    visited[there] = 1;
  }
  
}

// Do not edit the line below.
exports.primsAlgorithm = primsAlgorithm;
  • minHeap

time: O((E +V) * log) > O(ElogV) ElogV ⇒ 정점에 연결된 간선에 대해 각각 힙에 넣는 과정 VlogV ⇒ 매 정점마다 최소 간선 찾는 시간

Space: O(V + E)

Last updated