-
Notifications
You must be signed in to change notification settings - Fork 0
Closed
Description
π¬Β λ¬Έμ
https://www.acmicpc.net/problem/1260
π¬Β Idea
- DFSλ₯Ό μνν λ λ²νΈκ° μμ λ Έλλ€λΆν° μννκΈ° μν΄μ μν λ°°μ΄μ μ λ ¬ν λ€ λ€μ§μ΄μ μ μ₯ν΄μ€λ€.
- BFSλ₯Ό μνν λλ λ²νΈκ° μμ λ Έλλ€λΆν° μννκΈ° μν΄μ μν λ°°μ΄μ μ λ ¬νμ¬ μ μ₯ν΄μ€λ€.
π¬Β νμ΄
func solution1260() {
let info = readLine()!.split(separator: " ").map({ Int(String($0))! })
var graph: [Int: [Int]] = [:]
for _ in 0..<info[1] {
let nodes = readLine()!.split(separator: " ").map({ Int(String($0))! })
if graph[nodes[0]] == nil {
graph[nodes[0]] = [nodes[1]]
} else {
graph[nodes[0]]?.append(nodes[1])
}
if graph[nodes[1]] == nil {
graph[nodes[1]] = [nodes[0]]
} else {
graph[nodes[1]]?.append(nodes[0])
}
}
func dfs(graph: [Int: [Int]], start: Int) -> [Int] {
var needToVisitStack: [Int] = [start]
var visitedQueue: [Int] = []
while !needToVisitStack.isEmpty {
let node = needToVisitStack.removeLast()
if visitedQueue.contains(node) { continue }
visitedQueue.append(node)
if let nodes = graph[node]?.sorted().reversed() {
needToVisitStack += nodes
}
}
return visitedQueue
}
func bfs(graph: [Int: [Int]], start: Int) -> [Int] {
var needToVisitQueue: [Int] = [start]
var visitedQueue: [Int] = []
while !needToVisitQueue.isEmpty {
let node = needToVisitQueue.removeFirst()
if visitedQueue.contains(node) { continue }
visitedQueue.append(node)
if let nodes = graph[node]?.sorted() {
needToVisitQueue += nodes
}
}
return visitedQueue
}
print(dfs(graph: graph, start: info[2]).map({ String($0) }).joined(separator: " "))
print(bfs(graph: graph, start: info[2]).map({ String($0) }).joined(separator: " "))
}
μμμκ°
: 30λΆ