[코틀린] 21736 헌내기는 친구가 필요해

package 알고리즘.백준.헌내기는친구가필요해

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.*

val dx = intArrayOf(-1, 1, 0, 0)
val dy = intArrayOf(0, 0, -1, 1)

data class Position(val x: Int, val y: Int)

fun main() {
    val reader = BufferedReader(InputStreamReader(System.`in`))
    val writer = BufferedWriter(OutputStreamWriter(System.out))

    reader.use { r ->
        writer.use { w ->
            val (n, m) = r.readLine().split(" ").map { it.toInt() }
            val graph = Array(n) { CharArray(m) }
            val visited = Array(n) { BooleanArray(m) { false } }

            var doyeon = Position(0, 0)

            for (i in 0 until n) {
                val line = r.readLine()
                for (j in 0 until m) {
                    val value: Char = line[j]

                    if (value == Tile.DOYEON.value) {
                        doyeon = Position(i, j)
                    }

                    graph[i][j] = value
                }
            }

            bfs(graph, visited, doyeon, n, m).let { if (it > 0) println(it) else println("TT") }
        }
    }
}

fun bfs(campus: Array<CharArray>, visited: Array<BooleanArray>, doyeon: Position, n: Int, m: Int): Int {
    val queue: LinkedList<Position> = LinkedList()
    queue.add(doyeon)
    visited[doyeon.x][doyeon.y] = true

    var count = 0

    while (queue.isNotEmpty()) {
        val (x, y) = queue.poll()

        for (i in 0 until 4) {
            val nx = x + dx[i]
            val ny = y + dy[i]

            if (nx in 0 until n && ny in 0 until m && !visited[nx][ny]) {
                when (campus[nx][ny]) {
                    Tile.EMPTY.value -> {
                        visited[nx][ny] = true
                        queue.add(Position(nx, ny))
                    }

                    Tile.PERSON.value -> {
                        count++
                        visited[nx][ny] = true
                        queue.add(Position(nx, ny))
                    }
                }
            }
        }
    }

    return count
}

enum class Tile(val value: Char) {
    EMPTY('O'),
    WALL('X'),
    DOYEON('I'),
    PERSON('P')
}