#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int N, time_cnt = 0;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int visit[21][21];
pair <int, int> baby(2, 0);
pair <int, int> next_locate;
bool find_fish(vector <vector<int>> &shark) {
fill(&visit[0][0], &visit[21][0], 400);
int dist = 400;
bool flag = false;
queue <pair<int, int>> list;
int x = next_locate.first;
int y = next_locate.second;
visit[x][y] = 0;
list.push({x, y});
while(!list.empty()) {
int cx = list.front().first;
int cy = list.front().second;
list.pop();
for(int i=0; i<4; i++) {
int nx = cx + dir[i][0];
int ny = cy + dir[i][1];
if(nx < 0 || ny < 0 || nx >= N || ny >= N) continue;
if(shark[nx][ny] > baby.first) continue;
if(visit[nx][ny] == 400) {
list.push({nx, ny});
visit[nx][ny] = visit[cx][cy] + 1;
}
if(shark[nx][ny] != 0 && shark[nx][ny] < baby.first) {
flag = true;
dist = min(dist, visit[nx][ny]);
}
}
}
if(!flag) return false;
else {
bool check = false;
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
if(shark[i][j] == baby.first || shark[i][j] == 0) continue;
if(dist == visit[i][j]) {
shark[next_locate.first][next_locate.second] = 0;
next_locate = {i, j};
baby.second++;
if(baby.first == baby.second) {
baby.first++;
baby.second = 0;
}
shark[i][j] = 0;
time_cnt += dist;
check = true;
break;
}
}
if(check) break;
}
}
return true;
}
int main() {
cin >> N;
vector <vector<int>> shark(N, vector<int>(N));
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
cin >> shark[i][j];
if(shark[i][j] == 9) {
next_locate = {i, j};
}
}
}
while(1) {
bool check = find_fish(shark);
if(!check) break;
}
cout << time_cnt;
return 0;
}