require 'set'
h, w = gets.split.map(&:to_i)
a = (1..h).map { gets.split.map(&:to_i) }
pos = {}
(0..h-1).each do |i|
    (0..w-1).each do |j|
        pos[a[i][j]] = [i, j]
    end
end

goal = {}
(1..h*w).each do |k|
    i, j = pos[k]
    if i - 1 >= 0 and a[i-1][j] < k
        goal[k] ||= Set.new
        goal[k] += goal[a[i-1][j]]
    end
    if i + 1 < h and a[i+1][j] < k
        goal[k] ||= Set.new
        goal[k] += goal[a[i+1][j]]
    end
    if j - 1 >= 0 and a[i][j-1] < k
        goal[k] ||= Set.new
        goal[k] += goal[a[i][j-1]]
    end
    if j + 1 < w and a[i][j+1] < k
        goal[k] ||= Set.new
        goal[k] += goal[a[i][j+1]]
    end
    goal[k] ||= Set[k]
end

p goal.select {|_, v| v.size > 1}.size
