hdu 1728 逃离迷宫 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1728
BFS(转向限制)
题目大意:走迷宫,有转向次数限制。
题目分析:首先,要注意输入里的坑,每组样例最后五个数分别是最大转向次数、第一点的y值、第一点的x值、第二点的y值、第二点的x值。大体还是用以前的BFS思想来做,略有不同的地方是:
图例:
黑色为迷宫的两条路线;
红色为这一段所记的转向次数;
蓝色为start起始点。
注意那个跳跃的地方,对于已经走过的地方,应该跳过去,而不是另找一路,因为已走过的地方一定是可以走的,而已走过的点的turn值必然小于等于现在正在走的这条线,所以既不应该回头,又不应该直接走过去(其实这个题直接走过去我觉得也行,不会对答案造成影响,但道理说不通)。
code:
#include<cstdio>
#include<queue>
using namespace std;
char map[110][110],vis[110][110];
int m,n,maxturn,sx,sy,ex,ey;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node
{
int x,y,turn;
};
bool judge(int x,int y)
{
if(x>=0&&x<m&&y>=0&&y<n&&map[x][y]=='.')return true;
else return false;
}
bool bfs(int x,int y)
{
queue<node>que;
node first,next;
first.x=x,first.y=y,first.turn=-1;
que.push(first);
ex--,ey--;//0打头的处理
//printf("ex==%d,ey==%d\n",ex,ey);
while(!que.empty())
{
first=que.front();
que.pop();
if(first.turn>maxturn)return false;
for(int i=0;i<4;i++)
{
next.x=first.x+dir[i][0];
next.y=first.y+dir[i][1];
next.turn=first.turn+1;
while(judge(next.x,next.y))
{
if(vis[next.x][next.y]=='.')
{
next.turn=first.turn+1;
que.push(next);
vis[next.x][next.y]='*';
//printf("现在在:map[%d][%d],turn是%d,ex==%d,ey==%d,maxturn==%d\n",next.x,next.y,next.turn,ex,ey,maxturn);
if(next.x==ex&&next.y==ey&&next.turn<=maxturn)return true;
}
next.x+=dir[i][0];
next.y+=dir[i][1];
}
}
}
return false;
}
int main()
{
int t,i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
scanf("%s",map[i]);
strcpy(vis[i],map[i]);
}
scanf("%d%d%d%d%d",&maxturn,&sy,&sx,&ey,&ex);
printf("%s\n",bfs(sx-1,sy-1)?"yes":"no");
}
return 0;
}
PS:本来以为可以不用visit数组呢,结果最后还是得用,如果直接把走过的信息标记在原地图上,会造成错误,因为在本题中“走过”和“有墙”不能一概而论,情况不同。