HDU1728 逃離迷宮 【BFS】

逃離迷宮

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 16840    Accepted Submission(s): 4108


Problem Description
  給定一個m × n (m行, n列)的迷宮,迷宮中有兩個位置,gloria想從迷宮的一個位置走到另外一個位置,當然迷宮中有些地方是空地,gloria可以穿越,有些地方是障礙,她必須繞行,從迷宮的一個位置,只能走到與它相鄰的4個位置中,當然在行走過程中,gloria不能走到迷宮外面去。令人頭痛的是,gloria是個沒什麼方向感的人,因此,她在行走過程中,不能轉太多彎了,否則她會暈倒的。我們假定給定的兩個位置都是空地,初始時,gloria所面向的方向未定,她可以選擇4個方向的任何一個出發,而不算成一次轉彎。gloria能從一個位置走到另外一個位置嗎?
 

Input
  第1行爲一個整數t (1 ≤ t ≤ 100),表示測試數據的個數,接下來爲t組測試數據,每組測試數據中,
  第1行爲兩個整數m, n (1 ≤ m, n ≤ 100),分別表示迷宮的行數和列數,接下來m行,每行包括n個字符,其中字符'.'表示該位置爲空地,字符'*'表示該位置爲障礙,輸入數據中只有這兩種字符,每組測試數據的最後一行爲5個整數k, x1, y1, x2, y2 (1 ≤ k ≤ 10, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m),其中k表示gloria最多能轉的彎數,(x1, y1), (x2, y2)表示兩個位置,其中x1,x2對應列,y1, y2對應行。
 

Output
  每組測試數據對應爲一行,若gloria能從一個位置走到另外一個位置,輸出“yes”,否則輸出“no”。
 

Sample Input
2 5 5 ...** *.**. ..... ..... *.... 1 1 1 1 3 5 5 ...** *.**. ..... ..... *.... 2 1 1 1 3
 

Sample Output
no yes

#include <stdio.h>
#include <string.h>

#define maxn 105
const int dir[][2] = {0, 1, 0, -1, 1, 0, -1, 0};

struct Node {
	int x, y, step;
} que[maxn * maxn]; // 點不能重複入隊,但能重複走
int M, N, K, X, Y; // M rows
char G[maxn][maxn];

bool check(int x, int y) {
	return x >= 1 && x <= M && y >= 1 && y <= N && G[x][y] != '*';
}

bool BFS(int x0, int y0) {
	Node u, v;
	int front = 0, back = 0, i;

	G[x0][y0] = '*';
	u.x = x0; u.y = y0; u.step = -1;
	que[back++] = u;
	while (front != back) {
		u = que[front++];
		if (u.x == X && u.y == Y) return true;
		if (u.step == K) continue;
		for (i = 0; i < 4; ++i) {
			v = u;
			++v.step;
			while (true) {
				v.x += dir[i][0];
				v.y += dir[i][1];
				if (!check(v.x, v.y)) break;
				if (G[v.x][v.y] == '.') que[back++] = v;
				G[v.x][v.y] = '@'; // mark
			}
		}
	}
	return false;
} 

int main() {
	// freopen("stdin.txt", "r", stdin);
	int x0, y0, T, i;
	scanf("%d", &T);
	while (T--) {
		scanf("%d%d", &M, &N);
		for (i = 1; i <= M; ++i)
			scanf("%s", G[i] + 1);
		scanf("%d%d%d%d%d", &K, &y0, &x0, &Y, &X);
		puts(BFS(x0, y0) ? "yes" : "no");
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章