visitedStack을 [Int] contain방식 -> [bool] index체크방식 하여 시간 단축했다. 코드확인.
import Foundation
let given = readLine()!.split(separator: " ").map{Int(String($0))!}
let n = given[0]
let m = given[1]
var map : [Int:[Int]] = [:]
for i in 1...n {
map[i] = []
}
for _ in 0..<m {
let given = readLine()!.split(separator: " ").map{Int(String($0))!}
let n = given[0], m = given[1]
map[n]!.append(m)
map[m]!.append(n)
}
var result = 0
//var visited:[Int] = []
var visited : [Bool] = Array(repeating: false, count: 1001)
for i in map {
let node = i.key
if !visited[node]{
// if !visited.contains(node){
dfs(node)
result += 1
}
}
func dfs(_ node : Int) {
var needVisitedStack:[Int] = [node]
while(!needVisitedStack.isEmpty) {
let node = needVisitedStack.removeLast()
if visited[node]{continue}
else {
visited[node] = true
needVisitedStack += map[node] ?? []
}
}
}
print(result)