문제링크
문제풀이
function solution(n, costs) {
let answer =0;
costs.sort((a,b)=>a[0]===b[0]?a[1]-b[1]:a[0]-b[0]);
let edge=Array.from({length:n},()=>Array());
let vertex=new Set();
costs.forEach((cost)=>{
vertex.add(cost[0]).add(cost[1]);
})
vertex=[...vertex];
costs.forEach((cost)=>{
let x=vertex.indexOf(cost[0]);
let y=vertex.indexOf(cost[1]);
let w=cost[2];
edge[x].push([w,y]);
edge[y].push([w,x]);
})
let checked=Array(n).fill(0);
let heap=[[0,0]];
while (heap.length){
let [w, node]=heap.shift();
if(!checked[node]){
checked[node]=1;
answer+=w;
}
for(let e of edge[node]){
let w=e[0];
let nextnode=e[1];
if(!checked[nextnode]){
heap.push([w,nextnode]);
}
}
heap.sort((a,b)=>a[0]-b[0]);
}
return answer;
}