``````#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

const int INF = 110;

struct node
{
int x,  y;
};

int data[INF + 5][INF + 5];			//存地图

int bfs(int low, int high);		//广搜，看能否在海拔范围为low，high中找到一条合法路径

int judge(int diff);			//判断这个差值是否有效

int BinarySearch(int left, int right);	//二分的过程

int dir[4][2] = {-1,0,0,-1,1,0,0,1}; 	//广搜的方向

int vis[INF + 5][INF + 5] = {0};			//用来在标记已经搜索到的点

int N;

/*
5
1 1 3 6 8
1 2 2 5 5
4 4 0 3 3
8 0 2 3 4
4 3 0 2 1
*/
int main()
{
scanf("%d", &N);

for(int i = 1; i <= N ;i++)
{
for(int j = 1; j <= N; j++)
scanf("%d", &data[i][j]);
}

int result = BinarySearch(0,INF);

printf("%d\n", result);

return 0;
}

int BinarySearch(int left, int right)
{

while(left <= right)
{
int mid = (left + right) / 2;

if(judge(mid) == 1)
{
right = mid - 1;
}
else
{
left = mid + 1;
}

}

return left;

}

int judge(int diff)
{
for(int i = 0 ; i + diff <= INF ;i++)
{
if(bfs(i, i + diff) == 1)
{
return 1;
}
}
return 0;

}

int bfs(int low, int high)
{
memset(vis, 0, sizeof(vis));

node start; start.x = 1; start.y = 1;     //广搜的起点

if(!(data[1][1] >= low && data[1][1] <= high))
return 0;

queue <node> que;

que.push(start); vis[1][1] = 1;

while(!que.empty())
{
node now = que.front(); que.pop();

if(now.x == N && now.y == N)
return 1;

for(int i = 0 ; i < 4; i++)
{
int nx = now.x + dir[i][0];

int ny = now.y + dir[i][1];

if(nx >= 1&& nx <= N && ny >= 1 && ny <= N && data[nx][ny] >= low && data[nx][ny] <= high && vis[nx][ny] == 0)
{
vis[nx][ny] = 1;

node temp;temp.x = nx; temp.y = ny;

que.push(temp);

}
}
}
return 0;

}``````