๐Ÿ“ ์ฝ”ํ…Œ/BOJ

[Swift] ๋ฐฑ์ค€2606 ๋ฐ”์ด๋Ÿฌ์Šค

JerryiOS 2023. 4. 12. 01:11

import Foundation

/// N : ์ปดํ“จํ„ฐ์˜ ์ˆ˜ (์ •์ )
/// M : ๋„คํŠธ์›Œํฌ ์ƒ์—์„œ ์ง์ ‘ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ์ปดํ“จํ„ฐ์Œ์˜ ์ˆ˜ (๊ฐ„์„ )

let N = Int(readLine()!)!
let M = Int(readLine()!)!

var graph = [String: [String]]()
var cnt = 0

for i in 0..<N {
    graph[String(i+1)] = []
}

for _ in 0..<M{
    let ab = readLine()!.components(separatedBy: " ")
    let a = ab[0]
    let b = ab[1]
    graph[a]?.append(b)
    graph[b]?.append(a)
}

bfs("1")
print(cnt - 1)

func bfs(_ start: String) -> [String] {
    var visitedQueue: [String] = []
    var needVisitQueue: [String] = [start]
    
    while !needVisitQueue.isEmpty {
        let node: String = needVisitQueue.removeFirst()
        if visitedQueue.contains(node) { continue }
        
        visitedQueue.append(node)
        cnt += 1
        needVisitQueue += graph[node] ?? []
    }
    
    return visitedQueue
}

bfs๋กœ ๋ฐฉ๋ฌธํ•˜๋ฉด์„œ countํ•˜๋„๋ก ๊ฐ„๋‹จํ•˜๊ฒŒ ํ’€์—ˆ๋‹ค.

๋ฐ˜์‘ํ˜•