#include<bits/stdc++.h>
#define pii pair<int,int>
#define ff first
#define ss second
using namespace std;
bool color[505][505];
char arr[505][505];
int dist[505][505],m;
int x[] = {-1,+1,0,0};
int y[] = {0,0,+1,-1};
bool check(int r,int c)
{
if(r>=0 && r<m && c>=0 && c<m)
return true;
return false;
}
int bfs(pii source)
{
memset(color,false,sizeof color);
memset(dist,-1,sizeof dist);
color[source.ff][source.ss] = true;
dist[source.ff][source.ss] = 0;
queue<pii>Q;
Q.push(source);
while(!Q.empty())
{
pii now = Q.front();
Q.pop();
if(arr[now.ff][now.ss]=='3')
{
return dist[now.ff][now.ss];
}
int i,r,c;
for(i=0; i<4; i++)
{
r = x[i]+now.ff;
c = y[i]+now.ss;
if(check(r,c) && !color[r][c])
{
color[r][c] = true;
dist[r][c] = dist[now.ff][now.ss]+1;
Q.push(make_pair(r,c));
}
}
}
}
int main()
{
int i,j,res;
while(scanf("%d",&m)==1)
{
getchar();
for(i=0; i<m; i++)
{
gets(arr[i]);
}
res = 0;
for(i=0; i<m; i++)
{
for(j=0; j<m; j++)
{
if(arr[i][j]=='1')
{
res = max(res,bfs(make_pair(i,j)));
}
}
}
printf("%d\n",res);
}
return 0;
}