


fun main(args: Array<String>?) {
    fun Pair<Int, Int>.neighbor(): List<Pair<Int, Int>> {
        return listOf<Pair<Int, Int>>(first + 1 to second, first - 1 to second, first to second + 1, first to second - 1)
    }
    val (height, width) = readLine()!!.trim().split(' ').map(String::toInt)
    val state = Array(height){ readLine()!!.trim().split(' ').map(String::toInt)}
    val areas = (0 until height).flatMap{y -> (0 until width).map{x -> Pair(y, x)}}.sortedBy { state[it.first][it.second] }
    val memo = Array(height){Array(width){null as Pair<Int, Int>?} }
    var count = 0
    for (current in areas) {
        val neighbor = current.neighbor().filter{(i, j) -> i in 0 until height && j in 0 until width && state[current.first][current.second] > state[i][j] }.map{(i, j) -> memo[i][j] }
        if (neighbor.contains(null) || neighbor.distinct().size > 1) {
            ++count
        }else {
            memo[current.first][current.second] = neighbor.firstOrNull() ?: current
        }
    }
    println(count)
}
