#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> P;
typedef vector<ll> VI;
typedef vector<VI> VVI;
#define REP(i,n) for(ll i=0;i<(n);i++)
#define ALL(v) v.begin(),v.end()
template<typename T> bool chmax(T &x, const T &y) {return (x<y)?(x=y,true):false;};
template<typename T> bool chmin(T &x, const T &y) {return (x>y)?(x=y,true):false;};
constexpr ll MOD=998244353;
constexpr ll INF=2e18;

int dx[4]={1,0,-1,0}, dy[4]={0,1,0,-1};

int main(){
    int h, w, n; cin >> h >> w >> n;
    VVI c(h,VI(w));
    REP(i,h)REP(j,w) cin >> c[i][j], c[i][j]--;
    vector<vector<P>> p(n,vector<P>(0));
    REP(i,h)REP(j,w){
        p[c[i][j]].emplace_back(P{i,j});
    }
    VVI f(h,VI(w,0));
    queue<P> q;
    int ans=0;
    REP(i,n){
        bool no=0;
        for(auto j:p[i]){
            REP(k,4){
                int tx=j.first+dx[k], ty=j.second+dy[k];
                if(tx<0||tx>=h||ty<0||ty>=w)
                    continue;
                if(f[tx][ty]){
                    no=1;
                    break;
                }
            }
        }
        if(no){
            while(!q.empty()){
                f[q.front().first][q.front().second]=0;
                q.pop();
            }
            ans++;
        }
        for(auto j:p[i]){
            f[j.first][j.second]=1;
            q.push(j);
        }
    }
    if(!q.empty()) ans++;
    cout << ans << endl;
    return 0;
}