您的位置:首页 > 其它

hdu 1180 诡异的楼梯 (bfs)

2014-10-06 18:46 429 查看


诡异的楼梯

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)

Total Submission(s): 9360 Accepted Submission(s): 2309



Problem Description

Hogwarts正式开学以后,Harry发现在Hogwarts里,某些楼梯并不是静止不动的,相反,他们每隔一分钟就变动一次方向.

比如下面的例子里,一开始楼梯在竖直方向,一分钟以后它移动到了水平方向,再过一分钟它又回到了竖直方向.Harry发现对他来说很难找到能使得他最快到达目的地的路线,这时Ron(Harry最好的朋友)告诉Harry正好有一个魔法道具可以帮助他寻找这样的路线,而那个魔法道具上的咒语,正是由你纂写的.

Input

测试数据有多组,每组的表述如下:

第一行有两个数,M和N,接下来是一个M行N列的地图,'*'表示障碍物,'.'表示走廊,'|'或者'-'表示一个楼梯,并且标明了它在一开始时所处的位置:'|'表示的楼梯在最开始是竖直方向,'-'表示的楼梯在一开始是水平方向.地图中还有一个'S'是起点,'T'是目标,0<=M,N<=20,地图中不会出现两个相连的梯子.Harry每秒只能停留在'.'或'S'和'T'所标记的格子内.

Output

只有一行,包含一个数T,表示到达目标的最短时间.

注意:Harry只能每次走到相邻的格子而不能斜走,每移动一次恰好为一分钟,并且Harry登上楼梯并经过楼梯到达对面的整个过程只需要一分钟,Harry从来不在楼梯上停留.并且每次楼梯都恰好在Harry移动完毕以后才改变方向.

Sample Input

5 5
**..T
**.*.
..|..
.*.*.
S....


Sample Output

7

HintHint
地图如下:



终于A了,原来刚开始方向搞错了。

说下我的思路:从起点开始,碰到楼梯时判断是否和前进方向相同,若不同则等一分钟再前进,然后到达下一个位置。判断方向时可以用dir(方向)下标和时间的奇偶性。。。

#include"stdio.h"
#include"string.h"
#include"iostream"
#include"queue"
using namespace std;
#define N 25
const int inf=0x1f1f1f1f;
int dir[4][2]={1,0,0,-1,-1,0,0,1};
int n,m,mark

;
char g

;
struct node
{
int x,y,t;
friend bool operator<(node a,node b)
{
return a.t>b.t;
}
};
int bfs(int x,int y)
{
int i,di,dj;
priority_queue<node>q;
node cur,next;
cur.x=x;
cur.y=y;
cur.t=0;
mark[x][y]=0;
q.push(cur);
while(!q.empty())
{
cur=q.top();
q.pop();
if(g[cur.x][cur.y]=='T')
return cur.t;
for(i=0;i<4;i++)
{
next.x=di=dir[i][0]+cur.x;
next.y=dj=dir[i][1]+cur.y;
next.t=cur.t+1;
if(di<0||di>=n||dj<0||dj>=m||g[di][dj]=='*')
continue;
if(g[di][dj]=='|')
{
if(i==0||i==2)
{
if(cur.t%2)
next.t++;
}
else
{
if(cur.t%2==0)
next.t++;
}
next.x+=dir[i][0];
next.y+=dir[i][1];
if(mark[next.x][next.y]>next.t)
{
mark[next.x][next.y]=next.t;
q.push(next);
}
}
else if(g[di][dj]=='-')
{
if(i==1||i==3)
{
if(cur.t%2)
next.t++;
}
else
{
if(cur.t%2==0)
next.t++;
}
next.x+=dir[i][0];
next.y+=dir[i][1];
if(mark[next.x][next.y]>next.t)
{
mark[next.x][next.y]=next.t;
q.push(next);
}
}
else
{
if(mark[next.x][next.y]>next.t)
{
mark[next.x][next.y]=next.t;
q.push(next);
}
}
}
}
}
int main()
{
int i,j,si,sj;
while(scanf("%d%d",&n,&m)!=-1)
{
for(i=0;i<n;i++)
{
scanf("%s",g[i]);
for(j=0;j<m;j++)
{
if(g[i][j]=='S')
{
si=i;sj=j;
}
mark[i][j]=inf;
}
}
printf("%d\n",bfs(si,sj));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: