๊ธ€ ์ž‘์„ฑ์ž: ์ด์ง€์›๐ŸŒฉ๏ธ

๋ฌธ์ œ ๋…ํ•ด๋ฅผ ์ž˜๋ชปํ•ด์„œ ํ—ท๊ฐˆ๋ ธ๋˜ ๋ฌธ์ œ. ์—ฌํƒ€ bfs/dfs ๋ฌธ์ œ๋ž‘ ๋น„์Šทํ•˜๊ฒŒ ํ‘ธ๋Š”๋ฐ, ๋ฐ”๊นฅ์—์„œ ๋ชจ๋“  ์ปดํ“จํ„ฐ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ํ•œ ๋ฒˆ์ด๋ผ๋„ ๋ฐฉ๋ฌธํ•œ ๊ณณ์€ visited ๋ณ€์ˆ˜์— ๋‹ด์•„ ์ฒดํฌํ–ˆ๋‹ค. ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๊ณณ์€ ์ปดํ“จํ„ฐ๋ผ๋ฆฌ ์—ฐ๊ฒฐ๋˜์—ˆ๋‹ค๋Š” ๋œป์ด๋‹ˆ๊นŒ ใ…‡ใ…‡


๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/43162


๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

Swift

import Foundation

func solution(_ n:Int, _ computers:[[Int]]) -> Int {
    var graph = [Int: [Int]]()
    for i in 0..<n {
        graph[i] = []
    }
    for i in 0..<n {
        for j in 0..<n {
            if i == j {
                continue
            }
            if computers[i][j] == 1 {
                graph[i, default: []].append(j)
            }
        }
    }

    func bfs(_ start: Int) -> Set<Int> {
        var visited: Set<Int> = []
        var queue = [start]
        while !queue.isEmpty {
            let v = queue.removeFirst()
            for w in graph[v]! {
                if !visited.contains(w) {
                    visited.insert(w)
                    queue.append(w)
                }
            }
        }
        return visited
    }

    var visited: Set<Int> = []
    var answer = 0
    for i in 0..<n {
        if !visited.contains(i) {
            let v = bfs(i)
            for j in v {
                visited.insert(j)
            }
            answer += 1
        }
    }
    return answer
}
๋ฐ˜์‘ํ˜•