한 여덟시간? 안풀렸다. 집중을 못한 탓도 있다..
var n = Int(readLine()!)!
var connection = Int(readLine()!)!
var set :Set<Int> = [1]
var graph : [Int:[Int]] = Dictionary<Int,[Int]>()
for index in 0..<101 {
graph.updateValue([], forKey: index)
}//101개
//graph[3]!.append(3)//unwrap해야한다.
for index in 0..<connection {
var line = readLine()!.components(separatedBy: " ").map{Int($0)!}.sorted()
//print(line[0])
//print(line[1])
graph[line[0]]!.append(line[1])
graph[line[1]]!.append(line[0])
}
print(graph)
//print(graph.sorted{$0.key < $1.key})
//var needToGo = [1]
var visit:[Bool] = Array(repeating: false, count: n+1)//n+1개
//
//var needToGo = [Int]()//여기있으면안된다
var result = 0
func dfs(start : Int){
var needToGo = [Int]()
//print("현재지점: \(start)")
visit[start] = true
//print("중간 result: \(result)")
needToGo += graph[start]!
print("needToGo: \(needToGo)")
while !needToGo.isEmpty {
let node : Int = needToGo.removeLast()
print(node)
if visit[node] == true {
continue
}
visit[node] = true
needToGo += graph[node]!
result += 1
//print("\(result),\(node)에 의해")
}
}
for i in 1..<n+1 {
print(i)
if visit[i] == false {
dfs(start: i)
}
break
}
print(result)
잘못했던것.
1. 그래프를 만들때 한쪽방향만 만든것. 그러면 1->7->4 이런 식으로 가야할 때, 7->4 가 없고 4->7만 있으면 못가는 오류발생.
2. 딕셔너리 특정 자리 부를때는 언랩 해야한다.
graph[line[0]]!.append(line[1])