1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ์ ํ์ ์ธ ๊ทธ๋ํ ํ์ ๋ฌธ์ ๋ก DFS or BFS๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
- ์ธ์ ํ ๋ ธ๋๋ฅผ ๋ฐฉ๋ฌธํ ๋ ๋ง๋ค, count ๊ฐ์ ์ฆ๊ฐ์์ผ์ค์ผ๋ก์จ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์๊ณ , O(N + M)์ ์๊ฐ๋ณต์ก๋๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - ์ ๋ฐ์ด๋ฌ์ค
//MARK: - Framework
import Foundation
//MARK: - Type
struct Graph {
//MARK: - Property
var edges: [Int]
//MARK: - Initializer
init() {
self.edges = []
}
}
//MARK: - Variable
var graph: [Graph] = []
var visited: [Bool] = []
var count: Int = 0
//MARK: - Function
func dfs(_ x: Int) -> Void {
visited[x] = true
for i in 0..<graph[x].edges.count {
let y: Int = graph[x].edges[i]
if !visited[y] {
count += 1
dfs(y)
}
}
}
func solution() -> Void {
//MARK: - Input
guard let N: Int = Int(readLine() ?? "0") else { return }
guard let M: Int = Int(readLine() ?? "0") else { return }
graph = Array(repeating: Graph(), count: N + 10)
visited = Array(repeating: false, count: N + 10)
for _ in 0..<M {
guard let inputData = readLine()?.components(separatedBy: " ") else { return }
let a: Int = inputData.map { Int($0) }[0] ?? 0
let b: Int = inputData.map { Int($0) }[1] ?? 0
graph[a].edges.append(b)
graph[b].edges.append(a)
}
//MARK: - Process
dfs(1)
//MARK: - Output
print(count)
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.
'Swift Data Structure And Algorithm > Graph Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๊น์ด์ฐ์ ํ์๊ณผ ๋๋น์ฐ์ ํ์ (0) | 2022.04.15 |
---|---|
๋จ์ง ๋ฒํธ ๋ถ์ด๊ธฐ_DFS (0) | 2022.04.15 |
์ด๋ถ ๊ทธ๋ํ ํ๋ณ_DFS (0) | 2022.04.15 |
2์์น ํ๊ธฐ_DFS (0) | 2022.04.15 |
๊ทธ๋ํ ๊ตฌํ : ์ธ์ ๋ฆฌ์คํธ (0) | 2022.04.14 |