Mountain Walking
Time Limit: 1000MS | Memory Limit: 30000K |
---|
Description
Farmer John and Bessie the cow have embarked on one of those ‘active’ vacations. They spend entire days walking in the mountains and then, at the end of the day, they tire and return to their vacation cabin.
Since climbing requires a lot of energy and they are already tired, they wish to return to the cabin using a path that has the least difference between its highest and lowest elevations, no matter how long that path is. Help FJ find this easy-to-traverse path.
The map of the mountains is given by an N x N (2 <= N <= 100) matrix of integer elevations (0 <= any elevation <= 110) FJ and Bessie are currently at the upper left position (row 1, column 1) and the cabin is at the lower right (row N, column N). They can travel right, left, toward the top, or toward the bottom of the grid. They can not travel on a diagonal.
Input
- Line 1: The single integer, N
- Lines 2…N+1: Each line contains N integers, each of which specifies a square’s height. Line 2 contains the first (top) row of the grid; line 3 contains the second row, and so on. The first number on the line corresponds to the first (left) column of the grid, and so on.
Output
- Line 1: An integer that is the minimal height difference on the optimal path.
Sample Input
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
Sample Output
2
二分高度差,bfs
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int a[105][105], vis[105][105], n;
int dir[4][2]= {{1,0},{0,1},{0,-1},{-1,0}};
struct node
{
int x,y;
};
int bfs(int low, int up)
{
if(a[1][1]<low || a[1][1]>up)//如果起点在范围外,return 0
return 0;
queue<node>p;
while(!p.empty())
p.pop();
node t;
t.x=1, t.y=1;
p.push(t);//起点入队列
vis[1][1]=1;//标记
while(!p.empty())
{
node t1=p.front();
p.pop();
for(int i=0; i<4; i++)//四个方向
{
node t2;
t2.x=t1.x+dir[i][0], t2.y=t1.y+dir[i][1];//下一个方向的坐标
if(vis[t2.x][t2.y]||t2.x<1||t2.x>n||t2.y<1||t2.y>n)//如果该点曾访问过或者越界
continue;
vis[t2.x][t2.y]=1;
if(a[t2.x][t2.y]>=low&&a[t2.x][t2.y]<=up)//如果在范围内
{
p.push(t2);
if(t2.x==n&&t2.y==n)//到达终点
return 1;
}
}
return 0;
}
int judge(int m)//m是高度差
{
for(int low=0; low+m<=110; low++)//[low, low+m]高度范围
{
memset(vis, 0, sizeof(vis));
if(bfs(low, low+m))//在高度范围内搜索是否能到终点
return 1;
}
return 0;
}
int main()
{
scanf("%d", &n);
for(int i=1; i<=n; i++)
{
for(int j=1; j<=n; j++)
{
scanf("%d", &a[i][j]);
}
}
int l=0, r=110, m;
while(l<r)//二分高度差,根据反馈结果确定二分范围
{
m=(l+r)/2;//高度差
if(judge(m))//如果能走到终点,减小高度差,r=m
r=m;
else
l=m+1;
}
printf("%d\n", r);
return 0;
}