[Swift - ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฐฐ๋‹ฌ

2021. 5. 19. 18:50ใ†๐Ÿง‘๐Ÿป‍๐Ÿ’ป iOS ๊ฐœ๋ฐœ/Swift - Algorithm - Solutions

๋ฌธ์ œ ํ•ด์„


1๋ฒˆ ๋งˆ์„์— ์žˆ๋Š” ์Œ์‹์ ์—์„œ N๊ฐœ์˜ ๋งˆ์„์— ๋ฐฐ๋‹ฌ์„ ํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ฐ ๋งˆ์„๋“ค ์‚ฌ์ด์—๋Š” ์–‘๋ฐฉํ–ฅ ๋„๋กœ๊ฐ€ ์กด์žฌํ•˜๋Š”๋ฐ ๋„๋กœ ๋งˆ๋‹ค ์ง€๋‚˜๋Š” ์‹œ๊ฐ„์ด ์กด์žฌํ•ฉ๋‹ˆ๋‹ค. ์ฃผ์–ด์ง„ ๋„๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ ๋งˆ์„๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๊ณ  1๋ฒˆ ๋งˆ์„ ๋ถ€ํ„ฐ ๊ฐ ๋งˆ์„ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๊ฐ€ k ์ดํ•˜์ธ ๋งˆ์„๋“ค์˜ ๊ฐœ์ˆ˜๋“ค์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‹จ์ผ ์ถœ๋ฐœ์ง€์—์„œ ๊ฐ€์žฅ ์งง์€ ๊ฒฝ๋กœ๋ฅผ ์ฐพ๊ณ  ๊ฐ ๋งˆ์„ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋Š” ์–‘์ˆ˜์ด๋ฏ€๋กœ ๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•˜์—ฌ ๊ฐ ๋งˆ์„๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•œ ํ›„ k๊ฐ’ ์ดํ•˜์˜ ๋งˆ์„๋“ค์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ฉ๋‹ˆ๋‹ค.

๋ฌธ์ œ ํ’€์ด & ์ฝ”๋“œ


import Foundation

func solution(_ N:Int, _ road:[[Int]], _ k:Int) -> Int {

    // 1๋ฒˆ ๋งˆ์„๋กœ ๋ถ€ํ„ฐ ๊ฐ ๋งˆ์„๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ฐฑ์‹ ํ•  ๋ฐฐ์—ด, ์ตœ๋Œ€๊ฐ’์œผ๋กœ ์ดˆ๊ธฐํ™” ํ•ฉ๋‹ˆ๋‹ค.
    var distsFromFirstVillage = [Int](repeating: Int.max, count: N + 1)
    
    // ๊ทธ๋ž˜ํ”„๋Š” ์ธ์ ‘ํ–‰๋ ฌ์˜ ํ˜•ํƒœ๋กœ ๊ตฌํ˜„ํ•˜๊ณ  ํ–‰๋ ฌ ๊ฐ’์„ ์ด๋™ํ•˜๋Š” ๋ฐ ์†Œ์š”๋˜๋Š” ์‹œ๊ฐ„์œผ๋กœ ํ‘œํ˜„
    // ๊ฐ’์ด 0 ์ธ๊ฒฝ์šฐ ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
    var graph = [[Int]](repeating: [Int](repeating: 0, count: N + 1), count: N + 1)
    
    for data in road {
        let from = data[0]
        let to = data[1]
        let cost = data[2]
        
        if graph[from][to] == 0 {
            graph[from][to] = cost
            graph[to][from] = cost
        } else {
            // ๋ฌธ์ œ์—์„œ ํ•œ ๋งˆ์„์—์„œ ๋‹ค๋ฅธ ๋งˆ์„๊นŒ์ง€์˜ ๊ฒฝ๋กœ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ ์กด์žฌ
            // ๊ทธ๋Ÿฌ๋‚˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋งŒ์„ ํŒ๋‹จํ•˜๋ฉด ๋˜๋ฏ€๋กœ ์†Œ์š” ์‹œ๊ฐ„์ด ๊ฐ€์žฅ ์งง์€ ๊ฐ’์œผ๋กœ ๊ฐฑ์‹ 
            
            if cost < graph[from][to] {
                graph[from][to] = cost
                graph[to][from] = cost
            }
        }
        
    }
    
    // ๋‹ค์ต์ŠคํŠธ๋ผ ํ•จ์ˆ˜
    func dijkstara(start: Int) {
        var queue = [(Int, Int)]()
        // ์‹œ์ž‘์  ๊ฑฐ๋ฆฌ 0์œผ๋กœ ์ดˆ๊ธฐํ™”
        distsFromFirstVillage[start] = 0
        
        queue.append((1,distsFromFirstVillage[1]))
        
        while !queue.isEmpty {
            let cur = queue.first!.0
            let cost = queue.first!.1
            queue.removeFirst()
            for next in 1...N {
                // ๊ฒฝ๋กœ๊ฐ€ ์กด์žฌํ•˜๊ณ  ๋” ์งง์€ ์ด๋™ ์†Œ์š” ์‹œ๊ฐ„์ผ ๊ฒฝ์šฐ ๋ฐฐ์—ด์„ ๊ฐฑ์‹ ํ•ฉ๋‹ˆ๋‹ค.
                if graph[cur][next] != 0 && cost + graph[cur][next]  < distsFromFirstVillage[next] {
                    distsFromFirstVillage[next] = cost + graph[cur][next]
                    queue.append((next, distsFromFirstVillage[next]))
                }
            }
        }
    }
    
    dijkstara(start: 1)
    
    return distsFromFirstVillage.filter{$0 <= k}.count
}