Swift/알고리즘
[Swift] 백준 - 바이러스
힛해
2024. 9. 9. 05:18
728x90
https://www.acmicpc.net/problem/2606
import Foundation
func main() {
// 언래핑
guard let V = Int(readLine()!), let N = Int(readLine()!) else { return }
var graph = [[Int]](repeating: [], count: V+1)
for _ in 0..<N{
let XY = readLine()!.split(separator: " ").map { Int($0)! }
let x = XY[0]
let y = XY[1]
graph[x].append(y)
graph[y].append(x)
}
func bfs() {
var visited = [Bool](repeating: false, count: V+1)
var queue = [Int]()
var result = 0
queue.append(1)
while !queue.isEmpty{
let node = queue.removeFirst()
if !visited[node]{
visited[node] = true
result += 1
for i in graph[node]{
queue.append(i)
}
}
}
print(result-1)
}
bfs()
}
// main 함수 실행
main()