[Swift]プログラマー(Lv 3)-島をつなぐ


こんにちは!
https://programmers.co.kr/learn/courses/30/lessons/42861


に答える


最小身長木プリフェッチアルゴリズムで解く.
開始ノードが0であると仮定し、すべての島を通過する最低コストを求める.△出発点がどこにあっても.
import Foundation


func prim(_ graph: [Int: [(Int, Int)]], _ n: Int) -> Int {
    var check = Array(repeating: false, count: n)
    var pq: [(cost: Int, index: Int)] = []
    var minCost = 0
    
    // 0번 섬에서 시작한다고 가정
    check[0] = true
    
    // 0번섬과 인접한 섬 우선순위큐에 넣어줌
    for (adjacent, cost) in graph[0]! {
        pq.append((cost, adjacent))
    }
    
    while !pq.isEmpty {
        // 비용 기준으로 내림차순 정렬
        pq.sort { $0.cost > $1.cost }
        let minCostPop = pq.removeLast()
        let currentCost = minCostPop.cost
        let currentNode = minCostPop.index
        
        // 가지 않은 섬만 추가 
        if !check[currentNode] {
            check[currentNode] = true
            minCost += currentCost
            
            for (adjacent, cost) in graph[currentNode]! {
                if !check[adjacent] {
                    pq.append((cost, adjacent))
                }
            }
        }
    }
    
    return minCost
}


func solution(_ n:Int, _ costs:[[Int]]) -> Int {
    var answer = 0    
    var graph: [Int: [(Int, Int)]] = [:]
    
    // 양방향 graph 만들기
    for road in costs {
        let a = road[0]
        let b = road[1]
        let cost = road[2]
        
        if let _ = graph[a] {
            graph[a]!.append((b, cost))
        } else {
            graph[a] = [(b, cost)]
        }
        
        if let _ = graph[b] {
            graph[b]!.append((a, cost))
        } else {
            graph[b] = [(a, cost)]
        }
    }
    
    return prim(graph, n)
}