Mountain Walking ——dfs

Mountain Walking

Time Limit:1000MS  Memory Limit:65536K
Total Submit:66 Accepted:22

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
 
题目要求:地图中寻找一条(1,1)到(n,n)的路,不管路有多长,只要求路途中maxn-minn最小
#include <iostream>
using namespace std;
#define N 110

int n;
int map[N][N];
bool flag[N][N];
int maxn, minn;
int low, high;
bool find;
int l, r, m;

void dfs( int x, int y )
{
	if(x>n||y>n||x<1||y<1)
		return ;
	if(flag[x][y])
		return ;
	if(map[x][y]>high||map[x][y]<low)
		return ;
	if(x==n&&y==n)
	{
		find = true;
		return ;
	}
	flag[x][y]=true;
	dfs(x+1,y);
	dfs(x,y+1);
	dfs(x-1,y);
	dfs(x,y-1);
}

bool judge()//judge regard m(mid) as difference is ok
{
	for(low=minn;low<maxn;low++)
	{
		high=low+m;
		memset(flag,false,sizeof(flag));
		find=false;
		dfs(1,1);
		if(find)
			return true;
	}
	return false;
}

int main()
{
	while( scanf("%d", &n)!=EOF )
	{
		int i, j;
		maxn=-1;
		minn=111;
		for( i=1; i<=n; ++i )
		{
			for( j=1; j<=n; ++j )
			{
				scanf("%d", &map[i][j]);
				if( map[i][j]>maxn )
					maxn = map[i][j];
				if( map[i][j]<minn )
					minn = map[i][j];
			}
		}
		l = 0;
		r = 110;
		while( l<r )
		{
			m=(l+r)/2;
			if(judge())
				r=m;
			else
				l=m+1;
		}
		printf("%d/n",l);
	}
	return 0;
} 

你可能感兴趣的:(Integer,input,Path,each,Matrix,output)