Untitled

 avatar
unknown
plain_text
10 days ago
1.0 kB
1
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))
        
        for (i in 0 until 4) { // Try all four directions before stopping
            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] == '.' && Pair(nx, ny) !in visited) {
                x = nx
                y = ny
                break
            } else {
                directionIndex = (directionIndex + 1) % 4 // Rotate 90 degrees clockwise
            }
        }
        
        // If after checking all directions, no move was made, break the loop
        if (visited.contains(Pair(x, y))) {
            break
        }
    }
    
    return visited.size
}
Leave a Comment