import java.util.Scanner enum class Direction { NORTH { override fun moveFrom(row: Int, col: Int): Pair { return Pair(row-1, col) } }, SOUTH { override fun moveFrom(row: Int, col: Int): Pair { return Pair(row+1, col) } }, WEST { override fun moveFrom(row: Int, col: Int): Pair { return Pair(row, col-1) } }, EAST { override fun moveFrom(row: Int, col: Int): Pair { return Pair(row, col+1) } }; fun turnRight(): Direction { return when (this) { NORTH -> EAST EAST -> SOUTH SOUTH -> WEST WEST -> NORTH } } abstract fun moveFrom(row: Int, col: Int): Pair } val scanner = Scanner(System.`in`) val map = ArrayList>() var rows = 0 var guardRow = -1 var guardCol = -1 while (scanner.hasNextLine()) { val line = scanner.nextLine() val pos = line.indexOf('^') if (pos != -1) { guardRow = rows guardCol = pos } val chars = line.toCharArray().toTypedArray() map.add(chars) rows++ } var facing = Direction.NORTH var visitedCount = 0 walk@ while (true) { if (map[guardRow][guardCol] != 'X') { visitedCount++ } map[guardRow][guardCol] = 'X' var seeking = true do { val (nextRow, nextCol) = facing.moveFrom(guardRow, guardCol) if (nextRow < 0 || nextRow >= map.size || nextCol < 0 || nextCol >= map[nextCol].size) { break@walk } if (map[nextRow][nextCol] == '#') { facing = facing.turnRight() } else { guardRow = nextRow guardCol = nextCol seeking = false } } while (seeking) } println(visitedCount)