[백준] 11724번 - Swift

이창형·2023년 6월 1일
0

코드

let num = readLine()!.split(separator: " ").map{Int($0)!}
let N = num[0]
let M = num[1]

var graph = [Int:[Int]]()

for _ in 0..<M {
    let input = readLine()!.split(separator: " ").map{Int($0)!}
    let x = input[0]
    let y = input[1]

    if graph[x] != nil {
        graph[x]?.append(y)
    } else {
        graph[x] = [y]
    }

    if graph[y] != nil {
        graph[y]?.append(x)
    } else {
        graph[y] = [x]
    }
}

var visited = Array(repeating: false, count: N+1)
var answer = 0

func dfs (_ start: Int, _ count: Int) {
    visited[start] = true

    for i in graph[start] ?? [] {
        if !visited[i] {
            visited[i] = true
            dfs(i, count+1)
        }
    }
}


for i in 1...N {
    if !visited[i] {
    // dfs를 한 번 돌고 오면 그래프가 하나 있는 거니 answer에 +1
        dfs(i, 0)
        answer += 1
    }
}

print(answer)

회고

  • dfs의 코드는 이해를 했는데 상황에 맞게 조건을 설정하는게 아직 미숙하다
  • 계속 풀어보면 성장할 수 있을 것 같다..
profile
iOS Developer

0개의 댓글