今天,集训,我旁边的wyb死怼了这道题,然后我看了一下,嘲讽了一波,“这么简单的bfs,要是我绝对一发过”,然后直播打脸。。。最后是看了一下wyb的博客A掉的,好了,先发一下题面。。。
逃离迷宫
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 33577 Accepted Submission(s): 8199
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
题意很明确:通过有限次数的变换方向,是否能够走出迷宫。
思路:思路其实也很直接,用一个结构体存坐标,方向,还有转向次数,然后bfs搜就ok了。
当然啦,如果你直接这样做,不是mle就是wa。
接下来说说这个题目的坑点:
-
题目要看清楚,n,m分别表示行列,x,y表示列行。。。(我倒是没被这个坑)
-
这个bfs和一般的不一样,一个点可以遍历
两次!!!如果出现遍历到同一个点时,转向次数可能是不一样的,我们显然应该优先取转向次数最少的点。
然后我。。因为忘记注释freopen。。。wa了三发。。。尴尬。。。
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef double dl;
const int mod = 1e9 + 7;
const int N = 1e5 + 7;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int inf = 0x3f3f3f3f;
#define mem(a) memset(a,inf,sizeof a)
inline ll gcd(ll a,ll b) {return b ? gcd(b,a % b) : a;}
inline ll lcm(ll a,ll b) {return a / gcd(a,b) * b;}
inline double Euler(int n) {return log(n) + 1.0 / (2 * n) + 0.57721566490153286060651209;}
//inline ll inverse_feima(ll n) {return fpow(n,mod - 2);}
ll n,m,k,t,ans = 0,o = 0;
struct location{
int x,y,time,dir;
};
location s,e,p;
char a[201][201];
int f[500][500];
bool flag,tag;
int dx[4] = {1,0,-1,0};
int dy[4] = {0,1,0,-1};
void bfs()
{
mem(f);
queue<location> q;
q.push(s);
while(!q.empty()){
p = q.front();
if(!flag) break;
for(int i = 0;i < 4;++i){
if(p.x + dx[i] >= 0 && p.x + dx[i] < m && p.y + dy[i] >= 0 && p.y + dy[i] < n && (p.dir == -1 || p.time < k || p.dir == i) && a[p.y + dy[i]][p.x + dx[i]] == '.'){
location temp = p;
if(temp.dir != i && temp.dir != -1) temp.time++;
temp.dir = i;temp.x += dx[i];temp.y += dy[i];
if(temp.x == e.x && temp.y == e.y){
flag = false;
break;
}
if(f[temp.y][temp.x] >= temp.time){
q.push(temp);
f[temp.y][temp.x] = temp.time;
}
}
}
if(p.x == e.x && p.y == e.y) flag = false;
q.pop();
}
}
int main()
{
ios::sync_with_stdio(0);
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
cin >> t;
while(t--){
cin >> n >> m;
for(int i = 0;i < n;++i) cin >> a[i];
cin >> k >> s.x >> s.y >> e.x >> e.y;
s.time = 0;
s.dir = -1;
s.x--;s.y--;e.x--;e.y--;
flag = true;
bfs();
if(flag) cout << "no" << endl;
else cout << "yes" << endl;
}
return 0;
}