Kotlin/코딩테스트

[프로그래머스] 공원 산책 - kotlin

깨노비 2023. 4. 3. 00:04
728x90
반응형

지나다니는 길을 'O', 장애물을 'X'로 나타낸 직사각형 격자 모양의 공원에서 로봇 강아지가 산책을 하려합니다. 산책은 로봇 강아지에 미리 입력된 명령에 따라 진행하며, 명령은 다음과 같은 형식으로 주어집니다.

class Solution {
    
    fun solution(park: Array<String>, routes: Array<String>): IntArray {
        val maxRow = park.size
        val maxCol = park[0].length
        var currentRow: Int = -1
        var currentCol: Int = -1
        val parkList = mutableListOf<List<Char>>()

        for ((indexX, str) in park.withIndex()) {
            parkList.add(str.toList())

            if (currentRow == -1) {
                val indexY = str.indexOf('S')
                if (indexY >= 0) {
                    currentRow = indexX
                    currentCol = indexY
                }
            }
        }

        loop@for (str in routes) {
            val move = str[2].toString().toInt()
            when (str[0]) {
                'N' -> {
                    if (currentRow - move < 0) continue@loop

                    for (i in 1..move) {
                        if (parkList[currentRow - i][currentCol] == 'X') continue@loop
                    }

                    currentRow -= move
                }
                'S' -> {
                    if (currentRow + move >= maxRow) continue@loop

                    for (i in 1..move) {
                        if (parkList[currentRow + i][currentCol] == 'X') continue@loop
                    }

                    currentRow += move
                }
                'W' -> {
                    if (currentCol - move < 0) continue@loop

                    for (i in 1..move) {
                        if (parkList[currentRow][currentCol - i] == 'X') continue@loop
                    }

                    currentCol -= move
                }
                'E' -> {
                    if (currentCol + move >= maxCol) continue@loop

                    for (i in 1..move) {
                        if (parkList[currentRow][currentCol + i] == 'X') continue@loop
                    }

                    currentCol += move
                }
            }
        }

        return intArrayOf(currentRow, currentCol)
    }
}

 

728x90
반응형