반응형
https://www.acmicpc.net/problem/2606
import Foundation
public struct Queue<T> {
fileprivate var array = [T]()
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public mutating func enquque(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
if isEmpty {
return nil
} else {
return array.removeFirst()
}
}
public var front: T? {
return array.first
}
}
let n = Int(readLine()!)!
let m = Int(readLine()!)!
var list:[[Int]] = []
for _ in 1...m {
let l = readLine()!.split(separator: " ").map{ Int(String($0))! }
list.append(l)
}
var visited:[Bool] = Array.init(repeating: false, count: n)
var graph:[[Int]] = Array.init(repeating: [], count: n)
for l in list {
var ll = graph[l[0]-1]
ll.append(l[1]-1)
graph[l[0]-1] = ll
var lll = graph[l[1]-1]
lll.append(l[0]-1)
graph[l[1]-1] = lll
}
var queue = Queue<Int>()
func bfs(start: Int) {
queue.enquque(start)
visited[start] = true
while !queue.isEmpty {
guard let elem = queue.dequeue() else { return }
for i in graph[elem] {
if !visited[i] {
queue.enquque(i)
visited[i] = true
}
}
}
}
bfs(start: 0)
print(visited.filter{ $0 }.count-1)
반응형
'# 02 > Swift - CTP' 카테고리의 다른 글
[Swift] 백준! 11047번 - 동전 0 (0) | 2023.01.29 |
---|---|
[Swift] 백준! 2667번 - 단지번호붙이기 (0) | 2023.01.20 |
[Swift] 백준! 2178번 - 미로 탐색 (0) | 2023.01.19 |
[Swift] 백준! 1260번 - DFS와 BFS (0) | 2023.01.19 |
[Swift] 백준! 2061번 - 좋은 암호 (0) | 2023.01.16 |