#include <string>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
using namespace std;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
int board[N][N];
int vis[N][N];
for(int i=0;i<N;i++) {
fill(board[i], board[i]+N, 0);
fill(vis[i], vis[i]+N, 0);
for(int j=0;j<N;j++){
cin >> board[i][j];
}
}
vector<vector<pair<int,int>>> v;
int part = -1;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if(vis[i][j] || board[i][j] == 0) continue;
queue<pair<int,int>> q;
q.push({i,j});
vis[i][j] = 1;
part++;
vector<pair<int,int>> temp; temp.push_back({i,j});
v.push_back(temp);
while(!q.empty())
{
auto cur = q.front(); q.pop();
for(int dir=0;dir<4;dir++)
{
int ny = cur.first + dy[dir];
int nx = cur.second + dx[dir];
if(ny<0 or nx<0 or ny>=N or nx>=N) continue;
if(vis[ny][nx] || board[ny][nx] == 0) continue;
q.push({ny,nx});
vis[ny][nx] = 1;
v[part].push_back({ny,nx});
}
}
}
}
int ans = N+N;
for(int i=0;i<v.size()-1;i++)
{
for(int j=i+1;j<v.size();j++)
{
int MIN = N+N;
for(int k=0;k<v[i].size();k++)
{
auto fix = v[i][k];
for(int q=0;q<v[j].size();q++)
{
auto comp = v[j][q];
int val = abs(fix.first-comp.first) + abs(fix.second-comp.second) -1;
MIN = min(MIN,val);
}
}
ans = min(MIN, ans);
}
}
cout << ans;
return 0;
}