#include using namespace std; int h, w, n, a[1010][1010], dp[1 << 20], nxt[1 << 20], v[1 << 20]; template struct IO { char reader[sz], writer[sz]; char *now, *now2 = writer; IO() { reader[fread(reader, sizeof(char), sizeof(char) * sz, stdin)]; now = reader; } inline T read() { while(*now && *now <= 32) now++; if(*now == '-') { now++; T res = 0; while('0' <= *now and *now <= '9') { res = res * 10 + *now++ - '0'; } return -res; } else { T res = 0; while('0' <= *now and *now <= '9') { res = res * 10 + *now++ - '0'; } return res; } } inline void read(T &res) { while(*now && *now <= 32) now++; if(*now == '-') { now++; res = 0; while('0' <= *now and *now <= '9') { res = res * 10 + *now++ - '0'; } res = -res; } else { res = 0; while('0' <= *now and *now <= '9') { res = res * 10 + *now++ - '0'; } } } inline string read_str() { string res; while(*now and *now != '\n' and *now != ' ') res += *now++; now++; return res; } inline void write(T x, char margin = ' ') { if(x == 0) { putchar('0'); putchar(margin); return; } if(x < 0) { putchar('-'); x = -x; } while(x) { *now2 = '0' + x % 10; now2++; x /= 10; } do { now2--; putchar(*now2); } while(now2 != writer); putchar(margin); } inline void write_str(string s, char margin = ' ') { for(auto c : s) putchar(c); putchar(margin); } }; IO io; inline int read() { return io.read(); } inline void write(int x) { io.write(x); } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); h = read(), w = read(), n = read(); for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) a[i][j] = read(); for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) v[i * w + j] = a[i][j]; sort(v, v + h * w); unique(v, v + h * w); for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) a[i][j] = lower_bound(begin(v), begin(v) + n, a[i][j]) - begin(v); dp[0] = 1; for(int i = 0; i < n; i++) nxt[i] = n; for(int i = 0; i < h - 1; i++) for(int j = 0; j < w; j++) { auto [x, y] = minmax(a[i][j], a[i + 1][j]); if(x != y) nxt[x] = min(nxt[x], y); } for(int i = 0; i < h; i++) for(int j = 0; j < w - 1; j++) { auto [x, y] = minmax(a[i][j], a[i][j + 1]); if(x != y) nxt[x] = min(nxt[x], y); } for(int i = 0; i < n; i++) { dp[i + 1] = max(dp[i + 1], dp[i]); if(nxt[i] != n) dp[nxt[i]] = max(dp[nxt[i]], dp[i] + 1); } cout << dp[n] << endl; }