#include #include #include #include using namespace std; int main() { int h, w, n; cin >> h >> w >> n; vector C(h, vector(w)); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { int c; cin >> c; C[i][j] = c - 1; } vector > > adj(n); for (int c = 1; c < n; c++) adj[c-1].emplace_back(c, 0); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { if (i > 0) { if (const int a = C[i-1][j], b = C[i][j]; a != b) adj[min(a, b)].emplace_back(max(a, b), 1); } if (j > 0) { if (const int a = C[i][j-1], b = C[i][j]; a != b) adj[min(a, b)].emplace_back(max(a, b), 1); } } vector dp(n, 1); for (int i = 0; i < n; i++) for (auto [j, d] : adj[i]) dp[j] = max(dp[j], dp[i] + d); cout << dp.back() << '\n'; }