https://coderun.yandex.ru/problem/troop Средняя

Решение

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.LinkedList
import java.util.Queue

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

    val dimensions = reader.readLine().split(" ")
    val n = dimensions[0].toInt()
    val m = dimensions[1].toInt()

    val heights = Array(n) { IntArray(m) }
    for (r in 0 until n) {
        val rowHeights = reader.readLine().trim().split(" ")
        for (c in 0 until m) {
            heights[r][c] = rowHeights[c].toInt()
        }
    }

    val visited = Array(n) { BooleanArray(m) }
    var sinkComponentCount = 0

    val dr = intArrayOf(-1, 1, 0, 0)
    val dc = intArrayOf(0, 0, -1, 1)

    for (r in 0 until n) {
        for (c in 0 until m) {
            if (!visited[r][c]) {
                val currentHeight = heights[r][c]
                val componentCells = mutableListOf<Pair<Int, Int>>()
                val q: Queue<Pair<Int, Int>> = LinkedList()

                q.add(Pair(r, c))
                visited[r][c] = true

                while (q.isNotEmpty()) {
                    val (currentRow, currentCol) = q.poll()
                    componentCells.add(Pair(currentRow, currentCol))

                    for (i in 0..3) {
                        val nextRow = currentRow + dr[i]
                        val nextCol = currentCol + dc[i]

                        if (nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < m) {
                            if (heights[nextRow][nextCol] == currentHeight && !visited[nextRow][nextCol]) {
                                visited[nextRow][nextCol] = true
                                q.add(Pair(nextRow, nextCol))
                            }
                        }
                    }
                }

                var isSink = true
                for ((pr, pc) in componentCells) {
                    for (i in 0..3) {
                        val nr = pr + dr[i]
                        val nc = pc + dc[i]

                        if (nr >= 0 && nr < n && nc >= 0 && nc < m) {
                            if (heights[nr][nc] < currentHeight) {
                                isSink = false
                                break
                            }
                        }
                    }
                    if (!isSink) break
                }

                if (isSink) {
                    sinkComponentCount++
                }
            }
        }
    }

    writer.write(sinkComponentCount.toString())
    writer.newLine()
    reader.close()
    writer.close()
}