mountant walking

 avatar
duyvan
plain_text
2 years ago
3.1 kB
8
Indexable
Mountain Walking
Cho một bản đồ kích thước NxN (2 <= N <= 100), mỗi ô mang giá trị là độ cao của ô đó (0 <= độ cao <= 110). Bác John và bò Bessie đang ở ô trên trái (dòng 1, cột 1) và muốn đi đến cabin (dòng N, cột N). Họ có thể đi sang phải, trái, lên trên và xuống dưới nhưng không thể đi theo đường chéo. Hãy giúp bác John và bò Bessie tìm đường đi sao cho chênh lệch giữa điểm cao nhất và thấp nhất trên đường đi là nhỏ nhất.

 

Input

Dòng 1: Số test case

Dòng 2: N

N dòng tiếp theo chứa N số nguyên, mỗi số cho biết cao độ của một ô.

 

Output

In ra #test case và một số nguyên là chênh lệch độ cao nhỏ nhất.

 

Sample

 

Input

5

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

5

99 85 38 22 55

89 28 33 3 65

99 20 14 67 90

36 27 28 77 31

50 45 12 9 14

2

92 83

19 91

5

61 49 32 34 28

100 65 0 10 89

34 99 40 86 4

10 97 49 21 30

95 33 79 51 65

2

17 60

94 27

 

Output

#1 2

#2 85

#3 9

#4 50

#5 43

//==========================

#include<iostream>
using namespace std;
int dr[4] = {-1,1,0,0};
int dc[4] = {0,0,-1,1};
#define s 104
#define INF 1000000
int map[s][s],n,ans,vt[s][s],MaxValue;
int front ,rear;
int calDis(int n1,int n2){
	int temp = n1 - n2 ;
	if(temp >= 0) return temp;
	else return (-1 * temp);
}
struct point{
	int r,c;
};
point queue[1000000];
bool empty(){
	return front == rear;
}
void push(point data){
	queue[++rear] =data;
}
void pop(point &data){
	if(!empty()) data = queue[++front];
}

void init(){
	front = rear =-1;
	for (int i = 0; i < n ; i++){
		for (int j = 0; j < n; j++){
			vt[i][j] = 0;
		}
	}
}

bool bfs(int low,int hight){
	
	if (map[0][0] > hight || map[0][0] < low) return false;
	point dt = {0,0}; push(dt);
	while (!empty()){
		point cur; pop(cur);
		if (vt[cur.r][cur.c] == 0) {
			vt[cur.r][cur.c] = 1;
			for (int i = 0; i < 4; i++) {
				point temp;
				temp.r = cur.r + dr[i];
				temp.c = cur.c + dc[i];
				if (temp.r >= 0 && temp.r < n && temp.c >= 0 && temp.c < n && map[temp.r][temp.c] >= low && map[temp.r][temp.c] <= hight) {
					if (temp.r == n - 1 && temp.c == n - 1) return true;
					if (vt[temp.r][temp.c] == 0) push(temp);
				}
			}
		}
	}
	return false;
}
bool checkKc(int kc) {
	for (int i = 0; i + kc <= MaxValue; i++) {
		init();
		if (bfs(i, i + kc)) return true;
	}
	return false;
}
int main(){
	//freopen("MountainWalking.txt","r",stdin);
	int t;cin>>t;
	for (int tc = 0; tc < t; tc++){
		cin>>n;
		for (int i = 0; i < n; i++){
			for (int j = 0; j < n; j++){
				cin>>map[i][j];
				if(MaxValue < map[i][j]) MaxValue = map[i][j];
			}
		}
		int MinValue = 0;
		int high = MaxValue;
		while (high > MinValue) {
			int mid = (MinValue + high) / 2;
			if (checkKc(mid)) high = mid;
			else MinValue = mid + 1;
		}
		// output
		cout << "#" << tc +1 << " " << high << endl;
	}
	return 0;
}
Editor is loading...
Leave a Comment