題目大意:給一個 n*n 的迷宮,迷宮每一格有一個整數表示該點的難度值,求從(1,1)到(n,n)的所用路徑中,難度差最小是多少。
[cpp]
include<stdio.h>
#include<string.h>
#define N 101
#define INF 0x7fffffff
int map[N][N],visit[N][N];
int n,H,L,flag;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
void DFS(int x,int y)
{
int i,next_x,next_y;
if(flag)return ;
visit[x][y]=1;
if(map[x][y]<L || map[x][y]>H)
return ;
if(x==n && y==n){
flag=1;
return;
}
for(i=0;i<4;i++){
next_x=x+dir[i][0];
next_y=y+dir[i][1];
if(next_x>=1 && next_x<=n && next_y>=1 && next_y<=n && !visit[next_x][next_y]){
DFS(next_x,next_y);
}
}
}
int main()
{
int i,j;
int max,min;
int hight,mid,low;
while(scanf("%d",&n)!=EOF){
min=INF;
max=-1;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
scanf("%d",&map[i][j]);
if(map[i][j]<min)min=map[i][j];
if(map[i][j]>max)max=map[i][j];
}
}
hight=max-min;
low=0;
while(hight>=low){
mid=(hight+low)/2;
for(i=min;i<=max-mid;i++){
H=i+mid;L=i;flag=0;//搜索范圍[L,H](即[i,i+mid]),區間長度為mid,mid越大搜索范圍越大
memset(visit,0,sizeof(visit));
DFS(1,1);
if(flag)break;
}
if(i<=max-mid)hight=mid-1;//當前范圍內能找到,mid變小,縮小搜索范圍;
else low=mid+1;//當前范圍內找不到,擴大搜索范圍;
}
printf("%d\n",hight+1);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#define N 101
#define INF 0x7fffffff
int map[N][N],visit[N][N];
int n,H,L,flag;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
void DFS(int x,int y)
{
int i,next_x,next_y;
if(flag)return ;
visit[x][y]=1;
if(map[x][y]<L || map[x][y]>H)
return ;
if(x==n && y==n){
flag=1;
return;
}
for(i=0;i<4;i++){
next_x=x+dir[i][0];
next_y=y+dir[i][1];
if(next_x>=1 && next_x<=n && next_y>=1 && next_y<=n && !visit[next_x][next_y]){
DFS(next_x,next_y);
}
}
}
int main()
{
int i,j;
int max,min;
int hight,mid,low;
while(scanf("%d",&n)!=EOF){
min=INF;
max=-1;
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
scanf("%d",&map[i][j]);
if(map[i][j]<min)min=map[i][j];
if(map[i][j]>max)max=map[i][j];
}
}
hight=max-min;
low=0;
while(hight>=low){
mid=(hight+low)/2;
for(i=min;i<=max-mid;i++){
H=i+mid;L=i;flag=0;//搜索范圍[L,H](即[i,i+mid]),區間長度為mid,mid越大搜索范圍越大
memset(visit,0,sizeof(visit));
DFS(1,1);
if(flag)break;
}
if(i<=max-mid)hight=mid-1;//當前范圍內能找到,mid變小,縮小搜索范圍;
else low=mid+1;//當前范圍內找不到,擴大搜索范圍;
}
printf("%d\n",hight+1);
}
return 0;
}