#include #include #include #include #include #include #include #include #include #include #include #include #define debug_value(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << #x << "=" << x << endl; #define debug(x) cerr << "line" << __LINE__ << ":<" << __func__ << ">:" << x << endl; template inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; } template inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; } using namespace std; typedef long long ll; struct UnionFind { vector data; UnionFind(int size) : data(size, -1) {} bool unionSet(int x, int y) { x = root(x); y = root(y); if (x != y) { if (data[y] < data[x]) swap(x, y); data[x] += data[y]; data[y] = x; } return x != y; } bool findSet(int x, int y) { return root(x) == root(y); } int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); } int size(int x) { return -data[root(x)]; } }; bool topological_sort(vector> g, vector &order){ int n = g.size(); order.clear(); vector used(n, false); function dfs = [&](int v){ used[v] = true; for(int to : g[v]){ if(!used[to]) dfs(to); } order.push_back(v); }; for(int v = 0; v < n; v++){ if(!used[v]) dfs(v); } reverse(order.begin(), order.end()); vector inv_order(n); for(int i = 0; i < n; i++) inv_order[order[i]] = i; for(int v = 0; v < n; v++){ for(int u : g[v]){ if(inv_order[v] > inv_order[u]) return false; } } return true; } template class Compress{ public: vector data; int offset; Compress(vector data_, int offset=0): offset(offset){ set st; for(T x: data_) st.insert(x); for(T x: st) data.push_back(x); }; int operator[](T x) { auto p = lower_bound(data.begin(), data.end(), x); assert(x == *p); return offset+(p-data.begin()); } T inv(int x){ return data[x-offset]; } int size(){ return data.size(); } }; using P = pair; int dh[4] = {0, 0, -1, 1}; int dw[4] = {-1, 1, 0, 0}; int main(){ ios::sync_with_stdio(false); cin.tie(0); cout << setprecision(10) << fixed; int h, w, n; cin >> h >> w >> n; vector> c(h, vector(w)); vector> ans(h, vector(w)); map> mp; for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++){ cin >> c[i][j]; mp[c[i][j]].push_back(P(i, j)); } } auto is_in_field = [&](int i, int j){ return i >= 0 && i < h && j >= 0 && j < w; }; int cur = 1; for(int i = 1; i <= n; i++){ int tmp = cur; for(auto [x, y]: mp[i]){ int p = cur; for(int k = 0; k < 4; k++){ int x_to = x+dh[k]; int y_to = y+dw[k]; if(!is_in_field(x_to, y_to)) continue; if(c[x_to][y_to] == n) continue; chmax(p, ans[x_to][y_to]+1); } chmax(tmp, p); } for(auto [x, y]: mp[i]) ans[x][y] = tmp; cur = tmp; } cout << cur << endl; }