문제링크
import java.util.*
fun main() {
val bufferedReader = System.`in`.bufferedReader()
val bufferedWriter = System.out.bufferedWriter()
val (height, width) = bufferedReader.readLine().split(" ").map { it.toInt() }
val rectangle = mutableListOf<MutableList<Int>>()
for (i in 0 until height) {
val row = bufferedReader.readLine().split(" ").map { it.toInt() }.toMutableList()
rectangle.add(row)
}
var hour = 0
var numberOfRemainedCheese = 0
while (true) {
val numberOfCheese = getNumberOfCheese(height, width, rectangle)
val numberOfRemovedCheeseBoundary = getNumberOfRemovedCheeseBoundary(height, width, rectangle)
hour++
if (numberOfCheese == numberOfRemovedCheeseBoundary) {
numberOfRemainedCheese = numberOfCheese
break
}
}
bufferedWriter.write("$hour\n$numberOfRemainedCheese")
bufferedReader.close()
bufferedWriter.close()
}
fun getNumberOfCheese(height: Int, width: Int, rectangle: MutableList<MutableList<Int>>): Int {
var numberOfCheese = 0
for (i in 0 until height) {
for (j in 0 until width) {
if (rectangle[i][j] == 1) numberOfCheese++
}
}
return numberOfCheese
}
fun getNumberOfRemovedCheeseBoundary(height: Int, width: Int, rectangle: MutableList<MutableList<Int>>): Int {
var numberOfRemovedCheeseBoundary = 0
val dy = listOf(0, 1, 0, -1)
val dx = listOf(1, 0, -1, 0)
val visited = Array(height) { Array(width) { false } }
val queue: Queue<Pair<Int, Int>> = LinkedList()
queue.add(Pair(0, 0))
visited[0][0] = true
while (queue.isNotEmpty()) {
val (y, x) = queue.poll()
for (i in 0..3) {
val ny = y + dy[i]
val nx = x + dx[i]
if (ny in 0 until height && nx in 0 until width && !visited[ny][nx]) {
if (rectangle[ny][nx] == 0) {
queue.add(Pair(ny, nx))
visited[ny][nx] = true
} else {
rectangle[ny][nx] = 0
visited[ny][nx] = true
numberOfRemovedCheeseBoundary++
}
}
}
}
return numberOfRemovedCheeseBoundary
}
주석 없는 코드를 만들기 위해 노력하는 개발자입니다.
혹시라도 의도가 분명하지 않아보이는 (이해가 되지 않는) 코드가 있으시다면 편하게 답변 달아주시면 정말 감사하겠습니다.