Baekjoon algorithm training

[백준] 2606 (바이러스)

interfacer_han 2023. 12. 26. 14:43

#1 알고리즘

1

 

#2 코드 - 코틀린

fun main() {
    readln() // 컴퓨터의 갯수는 풀이에 사용하지 않는다.
    val connectionCount = readln().toInt()

    val connections : ArrayList<Array<Int>> = ArrayList()
    for(i : Int in 0..<connectionCount) {
        val digitChars = readln().split(" ")
        connections.add( arrayOf(digitChars[0].toInt(), digitChars[1].toInt()) )
    }

    val virusHosts : ArrayList<Int> = ArrayList()

    recursiveFindNextHost(connections, 1, virusHosts)

    println(virusHosts.size - 1) // 1번 컴퓨터 제외
}

fun recursiveFindNextHost(connections : ArrayList<Array<Int>>, computerNumber : Int, virusHosts : ArrayList<Int>) {
    virusHosts.addIfNotExist(computerNumber)

    for(i : Int in 0..<connections.size) {
        if(connections[i].contains(computerNumber)) {

            val anotherComputerNumber = if(connections[i][0] == computerNumber) { connections[i][1] } else { connections[i][0] }
            connections[i] = arrayOf(-1, -1) // connections[i]는 정보를 취했으니 이제 쓸모가 없다. 따라서, -1를 채워넣는다.

            recursiveFindNextHost(connections, anotherComputerNumber, virusHosts)
        }
    }
}

fun <T> ArrayList<T>.addIfNotExist(value: T) {
    if(!this.contains(value)) {
        this.add(value)
    }
}

가독성을 향상을 위해 확장함수를 사용했다.

'Baekjoon algorithm training' 카테고리의 다른 글

[백준] 18111 (마인크래프트)  (0) 2023.12.28
[백준] 2579 (계단 오르기)  (0) 2023.12.27
[백준] 1920 (수 찾기)  (0) 2023.12.25
[백준] 11723 (집합)  (0) 2023.12.21
[백준] 2108 (통계학)  (0) 2023.12.15