您的位置:首页 > 其它

[置顶] HDOJ 1728 逃离迷宫 (BFS )解题报告

2017-07-19 09:51 369 查看


逃离迷宫

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

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

 

一开始直接广搜结果发现有的样例会WA,而且效率特别低,QAQ 。单方向完全搜索就能AC了,代码如下:

#include<
b5ac
iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
using namespace std;
//HDOJ 1728
const int M = 101;
int n, m;
int va[10] = {0,0,1,-1};
int vb[10] = {1,-1,0,0};
int vis[101][101];
char maz[101][101];
struct point{
int px;
int py;
int change;
};
bool ans;
void bfs(int si,int sj,int ei,int ej,int mdir)
{
int i,a,b,j;
point tp,tem;
queue<point> q;
tp.px = si;
tp.py = sj;
tp.change = -1;    //这样就能一开始就是0次change了
q.push(tp);
vis[tp.px][tp.py] = 1;
while(!q.empty()){
tp = q.front();
q.pop();
if(tp.change==mdir) //因为后面有change + 1,之前有方向push过 所以等于就continue
continue;
tem.change = tp.change + 1;
for(i=0;i<4;i++){
a = tp.px + va[i];
b = tp.py + vb[i];
while(!(a<=0||b<=0||a>m||b>n||maz[a][b]=='*')){
if(!vis[a][b]){
vis[a][b]=1;
tem.px = a;
tem.py = b;
q.push(tem);
}
a += va[i];     //通过while循环一个方向走到不能再走
b += vb[i];
}
}
/*
for(i=1;i<=m;i++){      //释放该代码块后方便看到整个过程
for(j=1;j<=n;j++){
cout<<vis[i][j];
}
cout<<endl;
}
cout<<endl;
*/
if(vis[ei][ej]){    //是否走过出口
ans = true;
return;
}
}
return ;
}
int main()
{
int i,j;
int text, mturn, sti, stj, eni, enj;
scanf("%d",&text);
while(text--){
scanf("%d%d",&m,&n);
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
cin>>maz[i][j];
}
}
scanf("%d%d%d%d%d",&mturn,&stj,&sti,&enj,&eni); //注意行列先后顺序
memset(vis,0,sizeof(vis));
ans = false;
bfs(sti,stj,eni,enj,mturn);
if(ans)
printf("yes\n");
else
printf("no\n");
}
}

/*

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

Sample Output
no
yes

BFS的注意这个样例:
1
3 3
..*
...
*.*
1 1 1 3 2

yes

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: