#include using i32 = std::int32_t; using u32 = std::uint32_t; using i64 = std::int64_t; using u64 = std::uint64_t; using i128 = __int128_t; using u128 = __uint128_t; using isize = std::ptrdiff_t; using usize = std::size_t; class rep { struct Iter { usize itr; constexpr Iter(const usize pos) noexcept : itr(pos) {} constexpr void operator++() noexcept { ++itr; } constexpr bool operator!=(const Iter& other) const noexcept { return itr != other.itr; } constexpr usize operator*() const noexcept { return itr; } }; const Iter first, last; public: explicit constexpr rep(const usize first, const usize last) noexcept : first(first), last(std::max(first, last)) {} constexpr Iter begin() const noexcept { return first; } constexpr Iter end() const noexcept { return last; } }; constexpr u64 ceil_log2(const u64 x) { u64 e = 0; while (((u64)1 << e) < x) ++e; return e; } template class FenwickTree { usize logn; std::vector data; public: explicit FenwickTree(const usize size = 0) { logn = ceil_log2(size + 1) - 1; data = std::vector(size + 1, T(0)); } usize size() const { return data.size() - 1; } void add(usize i, const T& x) { assert(i < size()); i += 1; while (i < data.size()) { data[i] += x; i += i & -i; } } void subtract(usize i, const T& x) { assert(i < size()); i += 1; while (i < data.size()) { data[i] -= x; i += i & -i; } } T fold(usize l, usize r) const { assert(l <= r and r <= size()); T ret(0); while (l < r) { ret += data[r]; r -= r & -r; } while (r < l) { ret -= data[l]; l -= l & -l; } return ret; } template usize max_right(const F& f) const { assert(f(T(0))); usize i = 0; T sum(0); for (usize k = (1 << logn); k > 0; k >>= 1) { if (i + k <= size() && f(sum + data[i + k])) { i += k; sum += data[i]; } } return i; } }; template using Vec = std::vector; void main_() { usize H, W, N; std::cin >> H >> W >> N; Vec> grid(H, Vec(W)); for (auto& v : grid) { for (auto& x : v) { std::cin >> x; x -= 1; } } Vec> list(N); const auto add = [&](const usize x, const usize y) { if (x != y) { list[std::max(x, y)].push_back(std::min(x, y)); } }; for (const auto i : rep(0, H)) { for (const auto j : rep(1, W)) { add(grid[i][j - 1], grid[i][j]); } } for (const auto i : rep(1, H)) { for (const auto j : rep(0, W)) { add(grid[i - 1][j], grid[i][j]); } } FenwickTree fen(N - 1); for (const auto r : rep(0, N)) { for (const auto l : list[r]) { if (fen.fold(l, r) == 0) { fen.add(r - 1, 1); } } } std::cout << fen.fold(0, N - 1) + 1 << '\n'; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); main_(); return 0; }