#include<stdio.h>
#include<string.h>
int map[150][150],mmax,mmin,flag;
int n,bu[4][2]={1,0,-1,0,0,1,0,-1};
int Map1[150][150];
void dfs(int x,int y,int L,int R)
{
if(x==n&&y==n)
{
flag=1;
return;
}
int i,j;
for(i=0; i<4; i++)
{
int xx=x+bu[i][0];
int xy=y+bu[i][1];
if(map[xx][xy]>=L&&map[xx][xy]<=R&&Map1[xx][xy]==0)
{
Map1[xx][xy]=1;
dfs(xx,xy,L,R);
}
}
}
int find(int k)
{
int i,j;
for(i=mmin; i<=mmax-k; i++)
{
flag=0;
if(map[1][1]<i||map[1][1]>i+k)
continue;
if(map[n][n]<i||map[n][n]>i+k)//经过两个判断后,最大值为i+k,最小值为i,所以差值为k
continue;
memset(Map1,0,sizeof(Map1));
Map1[1][1]=1;
dfs(1,1,i,i+k);
if(flag)
return 1;
}
return 0;
}
int find_answer()
{
int i,j,x=0,y=mmax-mmin;
while(x<y)
{
int mid=(x+y)/2;
if(find(mid))
y=mid;
else
x=mid+1;
}
return y;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i,j;
mmax=-1;
mmin=999999;
memset(map,-1,sizeof(map));
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
{
scanf("%d",&map[i][j]);
if(mmax<map[i][j])
mmax=map[i][j];
if(mmin>map[i][j])
mmin= map[i][j];
}
printf("%d\n",find_answer());
}
return 0;
}
#include<string.h>
int map[150][150],mmax,mmin,flag;
int n,bu[4][2]={1,0,-1,0,0,1,0,-1};
int Map1[150][150];
void dfs(int x,int y,int L,int R)
{
if(x==n&&y==n)
{
flag=1;
return;
}
int i,j;
for(i=0; i<4; i++)
{
int xx=x+bu[i][0];
int xy=y+bu[i][1];
if(map[xx][xy]>=L&&map[xx][xy]<=R&&Map1[xx][xy]==0)
{
Map1[xx][xy]=1;
dfs(xx,xy,L,R);
}
}
}
int find(int k)
{
int i,j;
for(i=mmin; i<=mmax-k; i++)
{
flag=0;
if(map[1][1]<i||map[1][1]>i+k)
continue;
if(map[n][n]<i||map[n][n]>i+k)//经过两个判断后,最大值为i+k,最小值为i,所以差值为k
continue;
memset(Map1,0,sizeof(Map1));
Map1[1][1]=1;
dfs(1,1,i,i+k);
if(flag)
return 1;
}
return 0;
}
int find_answer()
{
int i,j,x=0,y=mmax-mmin;
while(x<y)
{
int mid=(x+y)/2;
if(find(mid))
y=mid;
else
x=mid+1;
}
return y;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
int i,j;
mmax=-1;
mmin=999999;
memset(map,-1,sizeof(map));
for(i=1; i<=n; i++)
for(j=1; j<=n; j++)
{
scanf("%d",&map[i][j]);
if(mmax<map[i][j])
mmax=map[i][j];
if(mmin>map[i][j])
mmin= map[i][j];
}
printf("%d\n",find_answer());
}
return 0;
}