POJ2110

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

本题大意是N*N矩阵中从左上角到右下角所经过的点的最大值与最小值之差最小是多少。
这里我采用二分和深搜的方法,代码如下:

#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
int n,t;
int date[110][110];//数据
int b[110][110];//是否走过
int f[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//方向
bool dfs(int l,int r,int x,int y){
    if(x==t&&y==t)return true;
    for(int i=0;i<4;i++){
        int ax,ay;
        ax=x+f[i][0];
        ay=y+f[i][1];
        if(ax<0||ax>t||ay<0||ay>t||b[ax][ay])continue;
        b[ax][ay]=1;
        if(date[ax][ay]>=l&&date[ax][ay]<=r)
            if(dfs(l,r,ax,ay))return true;
    }
    return false;
}
int main(){
    scanf("%d",&n);
    t=n-1;
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            scanf("%d",&date[i][j]);
        }
    }
    int mid,l=0,r=120,g,maxx=120;
    while(l<r){
        g=0;
        mid=(l+r)/2;
        int m=max(date[0][0]-mid,0);
        for(int i=m;i<=date[0][0];i++){//从起始点的值减差值(或0)到起始点的值加差值
            memset(b,0,sizeof(b));
            b[0][0]=1;
            if(dfs(i,i+mid,0,0)){
                g=1;break;
            }
        }
        if(g){
            maxx=min(maxx,mid);
            r=mid;
        }else l=mid+1;
    }
    printf("%d\n",maxx);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值