#include using namespace std; #define ll long long #define rep(i,n) for(int (i)=0;(i)<(n);(i)++) #define Pr pair #define Tp tuple using Graph = vector>; ll mod = 998244353; int main() { FILE *in = freopen("in/sample3.txt", "r", stdin); FILE *out = freopen("out/sample3.txt", "w", stdout); ll H,W,N; cin >> H >> W >> N; assert(1<=H&&H<=1000&&1<=W&&W<=1000&&1<=N&&N<=H*W); ll col[H][W]; set num; rep(i,H){ rep(j,W){ cin >> col[i][j]; assert(1<=col[i][j]&&col[i][j]<=2000000000); num.insert(col[i][j]); } } assert(num.size()==N); vector range; rep(i,H){ rep(j,W-1){ ll a = col[i][j], b = col[i][j+1]; if(a==b) continue; if(a>b) swap(a,b); range.push_back(make_pair(b,a)); } } rep(i,H-1){ rep(j,W){ ll a = col[i][j], b = col[i+1][j]; if(a==b) continue; if(a>b) swap(a,b); range.push_back(make_pair(b,a)); } } sort(range.begin(),range.end()); ll end = 0; ll ans = 1; for(auto p:range){ ll a = p.second, b = p.first; if(a>=end){ ans++; end = b; } } cout << ans << endl; }