1. ๋ฌธ์
2. ์ ์ถ๋ ฅ
3. ์ ์ถ๋ ฅ ์์
4. ๋ฌธ์ ์ค๊ณ
- ํน์ ๋ ธ๋์์๋ถํฐ ์์ํด์ ๊น์ด ์ฐ์ ํ์์ ์งํํ๊ฒ ๋๋ฉด, ํน์ ๋ ธ๋์์ ๋ค๋ฅธ ๋ชจ๋ ๋ ธ๋๊น์ง์ ๊ฑฐ๋ฆฌ๋ฅผ ์ ์ ์์
- ๋ฐ๋ผ์ ํธ๋ฆฌ๋ฅผ ๊ตฌ์ฑํ ๋ ๋ชจ๋ ๋ถ๋ชจ ์์ ๊ด๊ณ์ ๋ ธ๋๋ ์๋ก ์๋ฐฉํฅ์ผ๋ก ์ด์ด์ฃผ๊ณ , X ๋ ธ๋์์ ๋ถํฐ ๊น์ด ์ฐ์ ํ์์ ์งํํ๋ฉด์
- ๋ณ๋์ ๋ฐฐ์ด์ ๊ฑฐ๋ฆฌ๋ฅผ ์ ์ฅํจ์ผ๋ก์จ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์์
5. ์ ์ฒด ์ฝ๋
//MARK: - ํธ๋ฆฌ์์์ ๊ฑฐ๋ฆฌ
//MARK: - Framework
import Foundation
//MARK: - Type
struct Node {
//MARK: - Property
private var edges: [Int]
//MARK: - initializer
init() {
self.edges = []
}
//MARK: - Method
mutating func push(_ data: Int) -> Void {
self.edges.append(data)
}
func getNodeData(_ index: Int) -> Int {
return self.edges[index]
}
func size() -> Int {
return self.edges.count
}
}
//MARK: - Function
func dfs(_ tree: [Node], _ visited: inout [Bool], _ levels: inout [Int], _ node: Int, _ currentLevel: Int) -> Void {
visited[node] = true
levels[node] = currentLevel
for i in 0..<tree[node].size() {
let y: Int = tree[node].getNodeData(i)
if !visited[y] {
dfs(tree, &visited, &levels, y, currentLevel + 1)
}
}
}
func solution() -> Void {
//MARK: - Input
guard let input: [String] = readLine()?.components(separatedBy: " ") else { return }
let n: Int = input.map { Int($0) }[0] ?? 0
let X: Int = input.map { Int($0) }[1] ?? 0
let Y: Int = input.map { Int($0) }[2] ?? 0
var tree: [Node] = Array(repeating: Node(), count: n + 10)
var visited: [Bool] = Array(repeating: false, count: n + 10)
var levels: [Int] = Array(repeating: 0, count: n + 10)
var distance: Int = 0
for _ in 0..<n - 1 {
guard let inputData: [String] = readLine()?.components(separatedBy: " ") else { return }
let a: Int = inputData.map { Int($0) }[0] ?? 0
let b: Int = inputData.map { Int($0) }[1] ?? 0
tree[a].push(b)
tree[b].push(a)
}
//MARK: - Process
dfs(tree, &visited, &levels, X, 0)
distance = levels[Y]
//MARK: - Output
print(distance)
}
solution()
์ ์ฒด์ฝ๋๋ ์ฌ๊ธฐ์์ ํ์ธํ ์ ์์ต๋๋ค.
'Swift Data Structure And Algorithm > Tree' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํธ๋ฆฌ์ ๋์ด (0) | 2022.04.07 |
---|---|
๊ณตํต ์กฐ์ ์ฐพ๊ธฐ (0) | 2022.04.07 |
ํ์ ์ด์ฉํ ์ฐ์ ์์ ํ(Priority Queue By Heap) (0) | 2022.04.07 |
๋ฐฐ์ด์ ์ด์ฉํ ์ฐ์ ์์ ํ(Priority Queue By Array) (0) | 2022.04.06 |
ํธ๋ฆฌ ์ํ ๊ฒฐ๊ณผ ์ถ๋ ฅํ๊ธฐ (0) | 2022.04.06 |