# data[].attributes.body
老師好：超過10000公尺輸出睡在學校，那請問低於0有限制嗎？

# data[].attributes.body
請問那個灰點點是什麼意思？

# data[].attributes.body
https://docs.google.com/document/d/1rBwmCoPb282l2MbA9kPNI6Jipr90udmg3v5r0UoI68Y/edit?usp=sharing

# data[].attributes.body
#include<bits/stdc++.h>

#define int long long

using namespace std;

struct node{

int x, y;

};

int m, n, q, a[505][505], tx, ty, stp[505][505];

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

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

bool used[505][505];

int bound(int x, int y){

return x>=0 && x<m && y>=0 && y<n;

}

int bfs(int r){

queue<node> qq;

int res = 0;

stp[tx][ty] = r;

qq.push({tx, ty});

while(qq.size()){

if (res >= q) break;

int cx = qq.front().x;

int cy = qq.front().y;

qq.pop();

if(!used[cx][cy]) res++;

used[cx][cy] = 1;

if(stp[cx][cy] == 0) continue;

for(int i=0; i<4; i++){

int nx = cx+dx[i];

int ny = cy+dy[i];

if(bound(nx, ny) && !used[nx][ny] && a[nx][ny] > -1){

if(max(stp[cx][cy]-1, a[nx][ny]) > stp[nx][ny]){

stp[nx][ny] = max(stp[cx][cy]-1, a[nx][ny]);

qq.push({nx, ny});

}

}

}

}

return res;

}

signed main(){

ios::sync_with_stdio(0);

cin.tie(0);

cin >> m >> n >> q;

for(int i=0; i<m; i++){

for(int j=0; j<n; j++){

cin >> a[i][j];

if(a[i][j] == -2){

tx = i;

ty = j;

}

}

}

int l=0, r=n*m, ans=0;

while(l <= r){

int mid = (l+r)/2;

memset(used, 0, sizeof(used));

memset(stp, -1, sizeof(stp));

if(bfs(mid) >= q){

r = mid-1;

ans = mid;

}

else{

l = mid+1;

}

}

cout << ans << '\n';

return 0;

}