본문 바로가기

코딩 테스트/DFS

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

문제

컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.

 

풀이 과정

1. 1번 컴퓨터부터 연결되어 있는 N번 컴퓨터 DFS 탐색

2. 탐색한 컴퓨터는 중복탐색하지 않도록 따로 저장

3. 1번과 연결된 컴퓨터들에 대한 탐색이 종료되면 탐색하지 않은 컴퓨터를 기준으로 다시 탐색

 

코드

class Solution {
    val checkComputer = ArrayList<Int>()
    fun solution(n: Int, computers: Array<IntArray>): Int {
        var answer = 0
        
        for(i in computers.indices){
            if(checkComputer.contains(i)) continue 
            
            computers[i].forEachIndexed{ index, it ->
                if(it == 1) {
                    checkComputer.add(index)
                    checkNetWork(computers, index)
                }
            }
            answer++
        }
        
        return answer
    }
    
    fun checkNetWork(computers: Array<IntArray>, computer: Int){ 
        computers[computer].forEachIndexed{ index, it ->
            if(it == 1 && !checkComputer.contains(index)){
                checkComputer.add(index)
                checkNetWork(computers, index)
            }
        }
    }
}