본문 바로가기
알고리즘

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

by 고고 2022. 3. 17.

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

 

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

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

programmers.co.kr

 

 

dfs 기초 유형입니다.

import Foundation

func solution(_ n:Int, _ computers:[[Int]]) -> Int {
    var result = 0
    var visited = Array(repeating: false, count: n)
    
    func dfs(i: Int) {
        if !visited[i] { // 방문하지 않았다면, i와 연결된 모든 곳을 방문 처리.
            visited[i] = true
            
            for j in 0..<n {
                if computers[i][j] == 1 {
                    dfs(i: j) // i와 이어진 곳이 또 자신과 이어진 곳을 방문 처리.
                }
            }
        }
    }
    
    for i in 0..<n {
        if !visited[i] {
            result += 1
            dfs(i: i)
        }
    }
    
    return result
}

solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]) // 2
solution(2, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]) // 1

댓글