#include #define REP(i,n) for (int i=0;i<(n);++i) using namespace std; using pii = pair; template void amax(T& x, U y) {if (x < y) x = y;} const int dx[] = {1, 0, -1, 0}; const int dy[] = {0, 1, 0, -1}; int main() { cin.tie(0); ios::sync_with_stdio(false); int H, W, N; cin >> H >> W >> N; vector> C(H, vector(W)); vector> C_to_ij(N); REP(i, H) REP(j, W) { cin >> C[i][j]; --C[i][j]; C_to_ij[C[i][j]].emplace_back(i, j); } vector C_to_D(N); REP(k, N) { if (k) { amax(C_to_D[k], C_to_D[k - 1]); } for (auto [i, j] : C_to_ij[k]) { REP(d, 4) { int ni = i + dx[d]; int nj = j + dy[d]; if (0 <= ni && ni < H && 0 <= nj && nj < W && C[i][j] < C[ni][nj]) { amax(C_to_D[C[ni][nj]], C_to_D[k] + 1); } } } } int result = C_to_D[N - 1] + 1; cout << result << endl; return 0; }