Untitled
unknown
plain_text
13 days ago
1.2 kB
4
Indexable
fun solution(R: Array<String>): Int { val n = R.size val m = R[0].length val grid = Array(n) { BooleanArray(m) { false } } var x = 0 var y = 0 var dx = 1 var dy = 0 var cleanedCount = 0 var movesMade = 0 // Keep track of the number of moves to detect termination while (true) { if (!grid[x][y]) { grid[x][y] = true cleanedCount++ } val nextX = x + dx val nextY = y + dy if (nextX in 0 until n && nextY in 0 until m && R[nextX][nextY] == '.') { x = nextX y = nextY movesMade++ // Increment moves when a valid move is made } else { when { dx == 1 && dy == 0 -> { dx = 0; dy = 1 } dx == 0 && dy == 1 -> { dx = -1; dy = 0 } dx == -1 && dy == 0 -> { dx = 0; dy = -1 } dx == 0 && dy == -1 -> { dx = 1; dy = 0 } } movesMade++ // Increment moves even when changing direction (important!) } // Termination condition: No valid moves can be made anymore if (movesMade > n * m * 4) break // A safe upper bound for moves } return cleanedCount }
Editor is loading...
Leave a Comment