逃離迷宮
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 23452 Accepted Submission(s): 5760
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
題意:
給定m*n的迷宮,k為最大轉彎次數,問能否到達終點。
思路:
通常的BFS必定超時,這里以k為底進行BFS,每到達一個節點就4個方向走到底,更新沒到過的節點的轉彎數(原位置的轉彎數+1),保證找到的解是轉彎數最小的解。
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct Node {
int x, y;
};
const int maxn = 100 + 5;
char buf[maxn][maxn];
int turn[maxn][maxn];
int m, n;
int k, x, y, goalx, goaly;
int ud[4] = { -1, 1, 0, 0 };
int lr[4] = { 0, 0, -1, 1 };
bool check(const Node& node) {
if (node.x > 0 && node.x <= m && node.y > 0 && node.y <= n) {
if (buf[node.x][node.y] != '*')
return true;
}
return false;
}
bool bfs() {
queue<Node> que;
Node now;
Node tmp;
now.x = x;
now.y = y;
que.push(now);
while (!que.empty()) {
now = que.front();
que.pop();
for (int i = 0; i < 4; ++i) {
tmp.x = now.x + ud[i];
tmp.y = now.y + lr[i];
while (check(tmp)) {
if (turn[tmp.x][tmp.y] == -1) {
turn[tmp.x][tmp.y] = turn[now.x][now.y] + 1;
if (tmp.x == goalx && tmp.y == goaly && turn[tmp.x][tmp.y] <= k) {
return true;
}
que.push(tmp);
}
tmp.x += ud[i];
tmp.y += lr[i];
}
}
}
return false;
}
int main() {
int T;
while (scanf("%d", &T) != EOF) {
while (T--) {
memset(turn, -1, sizeof(turn));
scanf("%d%d", &m, &n);
for (int i = 1; i <= m; ++i)
scanf("%s", buf[i] + 1);
scanf("%d%d%d%d%d", &k, &y, &x, &goaly, &goalx);
if ((x == goalx && y == goaly) || bfs())
printf("yes\n");
else
printf("no\n");
}
}
return 0;
}