#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n, m, k;
int mov[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int a[N][N], dis[N][N];
struct node {
  int x, y;
  int dis;
};
vector<node> w[N * N];
void bfs(vector<node> &s) {
  vector<node> q;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) dis[i][j] = 1e9;
  int cnt = -1;
  q.push_back(s[++cnt]);
  for (int i = 0; i < q.size(); i++) {
    node v = q[i];
    while (cnt + 1 < s.size() && s[cnt + 1].dis <= v.dis) q.push_back(s[++cnt]);
    for (int i = 0; i < 4; i++) {
      node u = {v.x + mov[i][0], v.y + mov[i][1]};
      if (1 <= u.x && u.x <= n && 1 <= u.y && u.y <= m &&
          v.dis + 1 < dis[u.x][u.y])
        dis[u.x][u.y] = u.dis = v.dis + 1, q.push_back(u);
    }
  }
}
signed main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      scanf("%d", &a[i][j]),
          w[a[i][j]].push_back({i, j, a[i][j] == 1 ? i + j - 2 : (int)1e9});
  for (int i = 2; i <= k; i++) {
    if (w[i - 1].size() * w[i].size() <= n * m) {
      for (node &u : w[i])
        for (node v : w[i - 1])
          u.dis = min(u.dis, v.dis + abs(u.x - v.x) + abs(u.y - v.y));
    } else {
      vector<node> s;
      for (node v : w[i - 1]) s.push_back(v);
      bfs(s);
      for (node &u : w[i]) u.dis = dis[u.x][u.y];
    }
  }
  printf("%d\n", w[k][0].dis);
  return 0;
}
