๋ฐ์ํ
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ํ๋๋ก ๊ฐ๋จํ๊ฒ ํ์๋ค.
๋ฐ์ํ
'๐ ์ฝํ > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Swift] ๋ฐฑ์ค 11399 ATM (0) | 2023.04.12 |
---|---|
[Swift] ๋ฐฑ์ค2178 ๋ฏธ๋กํ์ (0) | 2023.04.12 |
[Swift] ๋ฐฑ์ค 1927 ์ต์ ํ (0) | 2023.04.11 |
[Swift] ๋ฐฑ์ค 1074 Z (0) | 2023.04.11 |
[Swift] ๋ฐฑ์ค2630 ๋๋์ผ ํฌ์ผ๋ชฌ ๋ง์คํฐ ์ด๋ค์ (0) | 2023.04.11 |