import Foundation
let NMV = readLine()!.components(separatedBy: " ").map { Int($0)! }
let N = NMV[0]
let M = NMV[1]
let V = NMV[2]
var graph = [String: [String]]()
initializeGraph()
for _ in 1...M {
let AB = readLine()!.components(separatedBy: " ")
let A = AB[0]
let B = AB[1]
graph[A]?.append(B)
graph[B]?.append(A)
}
printArray(DFS(start: String(V)))
printArray(BFS(start: String(V)))
func DFS(start: String) -> [String] {
var visitedQueue: [String] = []
var needVisitStack: [String] = [start]
while !needVisitStack.isEmpty {
let node: String = needVisitStack.removeLast()
if visitedQueue.contains(node) { continue }
visitedQueue.append(node)
// 스택은 removeLast()로 노드를 가져오기 때문에 정렬을 내림차순으로 해줘야 작은 수부터 뽑힘
needVisitStack += graph[node]?.sorted(by: { Int($0)! > Int($1)! }) ?? []
}
return visitedQueue
}
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)
needVisitQueue += graph[node]?.sorted(by: { Int($0)! < Int($1)! }) ?? []
}
return visitedQueue
}
func initializeGraph() {
for i in 1...N {
graph[String(i)] = [] // 그래프 초기화
}
}
func printArray(_ arr: [String]) {
for str in arr {
if str.hashValue == arr.last?.hashValue {
print(str)
} else {
print(str, terminator: " ")
}
}
}
반응형
'📝 코테 > BOJ' 카테고리의 다른 글
[Swift] 백준 1676 팩토리얼 0의 개수 (0) | 2023.03.30 |
---|---|
[Swift] 백준1012 유기농배추 (0) | 2023.03.30 |
[Swift] 백준1389 케빈 베이컨의 6단계 법칙 (0) | 2023.03.30 |
[Swift] 백준 11650 좌표 정렬하기 (0) | 2023.03.29 |
[Swift] 백준 10866 덱 (0) | 2023.03.29 |