您的位置:首页 > 其它

HDU 1180 诡异的楼梯 BFS

2016-02-23 21:31 453 查看
诡异的楼梯

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

Total Submission(s): 11643 Accepted Submission(s): 2891

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

都说用优先队列,好吧我还不懂什么是优先队列,参考大神代码,用队列写了一次,时间还是0MS。遍历每个点,用数组记录每个节点的时间,直到遍历完所有节点,就得到最优解。

用奇偶性判断是否可以直接走过梯子,或是在梯子前等待,遇到等待,则时间+1就可以。

好像没什么要注意的点了。。。

以下是一些测试数据

/*

5 5

**..T

*..

**|..

.

S..**

5 5

**..T

*..

**-..

.

S..**

5 5

.|.-T

--|

.*.|.

--*

S|.**

5 5

S….

-|-|-

…..

-|-|-

….T

1 3

S-T

1 3

S|T

1 5

S|.|T

1 5

S-.-T

1 5

S|.-T

1 5

S-.|T

1 3

S|T

1 3

S-T

答案是:

8 7 7 8 1 2 4 3 3 2 2 1

*/

#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int M,N;
char edge[25][25];
int visited[25][25];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int sx,sy,ex,ey;
int mina;
struct node{
int x,y;
int step;
};
int Judge(int x,int y,int t)
{
if(x<1||x>M||y<1||y>N||visited[x][y]<=t||edge[x][y]=='*')
return 1;
return 0;
}
void BFS()
{
queue<node>Q;
node cur,next;
cur.x=sx;
cur.y=sy;
cur.step=0;
visited[sx][sy]=0;
Q.push(cur);
while(!Q.empty())
{
cur=Q.front();
Q.pop();
if(edge[cur.x][cur.y]=='T')
{
if(visited[cur.x][cur.y]>cur.step)
visited[cur.x][cur.y]=cur.step;
}
for(int i=0;i<4;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
next.step=cur.step+1;
if(edge[next.x][next.y]=='|')
{
if(cur.x==next.x&&(cur.step&1)==0)//横着走碰到|
{
next.step++;
}
if(cur.y==next.y&&(cur.step&1)==1)//竖着走碰到-
{
next.step++;
}
next.x+=dir[i][0];
next.y+=dir[i][1];
}
else if(edge[next.x][next.y]=='-')
{
if(cur.x==next.x&&(cur.step&1)==1)//横着走
{
next.step++;
}
if(cur.y==next.y&&(cur.step&1)==0)//竖着走
{
next.step++;
}
next.x+=dir[i][0];
next.y+=dir[i][1];
}
if(Judge(next.x,next.y,next.step)==1)
continue;
visited[next.x][next.y]=next.step;
Q.push(next);
}
}
}
int main(int argc, char *argv[])
{

while(cin>>M>>N)
{
for(int i=1;i<=M;i++)
for(int j=1;j<=N;j++)
{cin>>edge[i][j];
if(edge[i][j]=='S')
{
sx=i;
sy=j;
}
else if(edge[i][j]=='T')
{
ex=i;
ey=j;
}
}
for(int i=0;i<25;i++)
for(int j=0;j<25;j++)
visited[i][j]=999;
mina=999;
BFS();
cout<<visited[ex][ey]<<endl;

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