프로그래머스

[프로그래머스] 스위프트 네트워크

Hani_Levenshtein 2021. 10. 30. 14:54

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

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있

programmers.co.kr

 

import Foundation

func solution(_ n:Int, _ computers:[[Int]]) -> Int {
    
    var visited: [Bool] = Array(repeating: false, count: n)
    var network: Int = 0
 
    func bfs(_ computer: Int) {
        visited[computer] = true
        
        for i in 0..<n {
            if computers[computer][i] == 1 && visited[i] == false {
                bfs(i)
            }
        }
    }
 
    for i in 0..<n {
        if !visited[i] {
            network += 1
            bfs(i)
        }
    }
 
    return network
}