HDU-1180 诡异的楼梯
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 131072/65536 K (Java/Others)
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
地图如下:
题目网址:http://acm.hdu.edu.cn/showproblem.php?pid=1180
分析
题意:中文题就不多说了,应该都可以看的懂。
思路:一个普通的搜索题,找从一个位置到另外一个位置的最小步数,只不过中间有一个楼梯需要注意,需要判断是不是可以直接通过楼梯,如果不可以就需要等一分钟(多消耗了一分钟),如果可以就直接通过楼梯到达楼梯对面的一个位置,这就说明只用了1分钟就走了2步,所以要用到优先队列。
代码
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
struct node
{
int x, y, pre;
friend bool operator < (node a,node b)
{
return a.pre>b.pre;
}
};
char dt[22][22];
int temp[22][22],t,xy[4][2]={0,1,1,0,0,-1,-1,0},m,n;
int place(int xt,int yt)
{
if (xt<0||xt>=m||yt<0||yt>=n||dt[xt][yt]=='*')
return 1;
return 0;
}
int direction(node now,node next)// 根据刚开始时梯子的方向
判断要通过梯子时梯子的方向
{
int pre;
if (dt[next.x][next.y]=='|')
pre=1;
else
pre=0;
pre+=now.pre%2;
return pre%2;
}
int BFS(int x,int y)
{
priority_queue<node>it;
memset(temp,0,sizeof(temp));
node o,e;
e.x=x;
e.y=y;
e.pre=0;
temp[e.x][e.y]=1;
it.push(e);
while (!it.empty())
{
e=it.top();
it.pop();
if (dt[e.x][e.y]=='T')
return e.pre;
for (int i=0;i<4;i++)
{
o.x=e.x+xy[i][0];
o.y=e.y+xy[i][1];
o.pre=e.pre+1;
if (place(o.x,o.y)||temp[o.x][o.y])
continue;
else if (dt[o.x][o.y]=='.'||dt[o.x][o.y]=='T')
{
temp[o.x][o.y] = 1;
it.push(o);
continue;
}
else
{
if (direction(e,o)!=(i%2)) //如果不能直接通过梯子
o.pre++;
o.x+=xy[i][0];
o.y+=xy[i][1];
if (place(o.x,o.y)||temp[o.x][o.y])
continue;
else
{
temp[o.x][o.y] = 1;
it.push(o);
}
}
}
}
return -1;
}
int main()
{
int xq,yq;
while (~scanf("%d %d",&m,&n))
{
for (int i=0;i<m;i++)
{
getchar();
for (int j = 0;j<n;j++)
{
scanf("%c", &dt[i][j]);
if (dt[i][j]=='S')
{
xq=i;yq=j;
}
}
}
printf("%d\n",BFS(xq,yq));
}
return 0;
}