您的位置:首页 > 其它

hdu 1728 逃离迷宫(BFS)

2014-07-28 22:20 477 查看
hdu 1728 逃离迷宫

 题意:从S点广搜,但路线的转折个数不超过K,看能否到达T点!

             注意输入的时候先是列,再是行

解题思路:注意控制转角,然后同一个点可能经过两次!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define M 102
#define INF 1<<29

int m,n,limit;
struct point
{
int x,y;
int dir;
int step;
bool operator ==(const point &b)const
{
return x==b.x&&y==b.y;
}
void input()
{
scanf("%d%d",&y,&x);
x--;y--;
}
bool ok()
{
return x>=0&&x<n&&y>=0&&y<m;
}
} s,e;
char mymap[M][M];
int vis[M][M];
int dir[4][2]= {{0,1},{0,-1},{1,0},{-1,0}}; //方向依次为右、左、下、上
int BFS()
{
if(s==e)return 1;
queue<point> q;
point pre,now;
s.dir=-1;
s.step=0;
vis[s.x][s.y]=0;
q.push(s);
while(!q.empty())
{
pre=q.front();
//printf("%d %d 转弯次数:%d\n",pre.x,pre.y,pre.step);
q.pop();
for(int i=0; i<4; i++)
{
now.x=pre.x+dir[i][0];
now.y=pre.y+dir[i][1];
now.dir=i;
now.step=pre.step;
if(pre.dir!=-1&&pre.dir!=now.dir)
now.step++;
if(now.ok()&&now.step<=limit&&mymap[now.x][now.y]=='.'&&
now.step<=vis[now.x][now.y])
{
if(now==e)return 1;
q.push(now);
vis[now.x][now.y]=now.step;
}
}
}
return 0;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
scanf("%s",mymap[i]);
scanf("%d",&limit);
s.input();
e.input();
if(mymap[s.x][s.y]!=mymap[e.x][e.y]||mymap[s.x][s.y]=='*')
{
printf("NO\n");
continue;
}
for(int i = 0; i <= n; i++)
for(int j = 0; j <= m; j++)
vis[i][j] = INF;
printf("%s\n",BFS()?"yes":"no");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: