import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int N, sy, sx, sSize, sEatCnt, ans;
static int[][] map;
static Queue<Node> queue = new ArrayDeque<>();
static boolean[][] visit;
static int[] dy = { -1, 1, 0, 0 };
static int[] dx = { 0, 0,-1, 1 };
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new int[N][N];
visit = new boolean[N][N];
for (int i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
int n = Integer.parseInt(st.nextToken());
if( n == 9 ) {
sy = i; sx = j;
}
map[i][j] = n;
}
}
sSize = 2;
while(true) {
int dis = bfs();
if( dis == 0 ) break;
ans += dis;
}
System.out.println(ans);
}
static int bfs() {
int minY = Integer.MAX_VALUE;
int minX = Integer.MAX_VALUE;
int minDis = Integer.MAX_VALUE;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
visit[i][j] = false;
}
}
visit[sy][sx] = true;
queue.offer(new Node(sy, sx, 0));
while( ! queue.isEmpty() ) {
Node node = queue.poll();
int y = node.y;
int x = node.x;
int d = node.d;
if( map[y][x] != 0 && map[y][x] < sSize ) {
if( d < minDis ) {
minDis = d;
minY = y;
minX = x;
}else if( d == minDis ) {
if( y < minY ) {
minDis = d;
minY = y;
minX = x;
}else if( y == minY ) {
if( x < minX ) {
minDis = d;
minY = y;
minX = x;
}
}
}
}
if( d + 1 >= minDis ) continue;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if( ny < 0 || nx < 0 || ny >= N || nx >= N
|| visit[ny][nx] || map[ny][nx] > sSize ) continue;
visit[ny][nx] = true;
queue.offer(new Node(ny, nx, node.d + 1));
}
}
if( minDis == Integer.MAX_VALUE ) return 0;
else {
sEatCnt++;
if( sEatCnt == sSize ) {
sSize++;
sEatCnt = 0;
}
map[minY][minX] = 0;
map[sy][sx] = 0;
sy = minY;
sx = minX;
}
return minDis;
}
static class Node{
int y, x, d;
Node(int y, int x, int d){
this.y = y; this.x = x; this.d =d;
}
}
}