#include #include #include #include #include int main() { int H, W; std::cin >> H >> W; std::vector> A(H, std::vector(W)); for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { std::cin >> A[i][j]; } } std::vector> to(H*W); for (int x = 0; x < H*W; ++x) { int i = x / W, j = x % W; int di[] = {1, 0, -1, 0}; int dj[] = {0, 1, 0, -1}; for (int k = 0; k < 4; ++k) { int ni = i + di[k], nj = j + dj[k]; if (0 <= ni && ni < H && 0 <= nj && nj < W && A[ni][nj] > A[i][j]) { to[x].insert(ni*W+nj); } } } std::vector indegree(H*W, 0); for (int x = 0; x < H*W; ++x) { for (auto y : to[x]) { indegree[y]++; } } std::queue q; std::vector B; for (int x = 0; x < H*W; ++x) { if (indegree[x] == 0) { q.push(x); B.push_back(x); } } std::vector order; while (!q.empty()) { int x = q.front(); q.pop(); order.push_back(x); for (auto y : to[x]) { indegree[y]--; if (indegree[y] == 0) { q.push(y); } } } int ans = 0; for (auto x : B) { int i = std::find(order.begin(), order.end(), x) - order.begin(); std::vector dist(H*W, -1); dist[x] = 1; while (i < order.size()) { x = order[i++]; for (auto y : to[x]) { if (dist[y] < dist[x] + 1) { dist[y] = dist[x] + 1; } } } ans = std::max(ans, *std::max_element(dist.begin(), dist.end())); } std::cout << ans << std::endl; return 0; }