Untitled

 avatar
unknown
plain_text
11 days ago
1.0 kB
2
Indexable
fun solution(R: Array<String>): Int {
    val n = R.size
    val m = R[0].length
    val directions = listOf(Pair(0, 1), Pair(1, 0), Pair(0, -1), Pair(-1, 0))
    var directionIndex = 0 // Starts facing right
    var x = 0
    var y = 0
    val visited = mutableSetOf<Pair<Int, Int>>()
    
    while (true) {
        visited.add(Pair(x, y))
        val (dx, dy) = directions[directionIndex]
        val nx = x + dx
        val ny = y + dy
        
        if (nx in 0 until n && ny in 0 until m && R[nx][ny] == '-') {
            x = nx
            y = ny
        } else {
            directionIndex = (directionIndex + 1) % 4 // Rotate 90 degrees clockwise
            val (newDx, newDy) = directions[directionIndex]
            val newX = x + newDx
            val newY = y + newDy
            if (newX !in 0 until n || newY !in 0 until m || R[newX][newY] != '-') {
                break // The robot is stuck in a loop
            }
            x = newX
            y = newY
        }
    }
    
    return visited.size
}
Leave a Comment