题目
hduoj1180
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
一、分析
乍一看以为是普通的最短路问题,结果这个楼梯确实有点诡异,而且这个题目是可以在楼梯通过不了时停下来等的,大概就是,如果可以通过就通过,且不计入时间,如果通过不了,就停下来等此时step就要+2.
二、代码
自己写了很久都没过,借鉴了别人的代码
代码如下(示例):
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
using namespace std;
char map[30][30];
int vis[30][30];
struct node
{
int x,y,step;
/*
bool operator <(const node &t)const
{
return step>t.step;
}*/
friend bool operator<(node n1,node n2)//优先队列
{
return n1.step>n2.step;//升序
}
};
int dir[4][2]={
0,1,0,-1,1,0,-1,0};
int m,n;
int sx,sy;
void bfs()
{
priority_queue<node>q;
node now,next;
now.x=sx;
now.y=sy;
now.step=0;
q.push(now);
vis[sx][sy]=1;
while(!q.empty())
{
now=q.top();
q.pop();
if(map[now.x][now.y]=='T')
{
cout<<now.step<<endl;
return;
}
for(int i=0;i<4;i++)
{
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
if(next.x<0||next.y<0||next.x>=m||next.y>=n||vis[next.x][next.y]==1)
continue;
if(map[next.x][next.y]=='|')
{
if(now.step%2==0&&(i==2||i==3))
{
next.x=next.x+dir[i][0];
next.y=next.y+dir[i][1];
}
else if(now.step%2==1&&(i==0||i==1))
{
next.x=next.x+dir[i][0];
next.y=next.y+dir[i][1];
}
else
{
next.x=next.x+dir[i][0];
next.y=next.y+dir[i][1];
vis[next.x][next.y]=1;
next.step=now.step+2;
q.push(next);
continue;
}
}
if(map[next.x][next.y]=='-')
{
if(now.step%2==1&&(i==2||i==3))
{
next.x=next.x+dir[i][0];
next.y=next.y+dir[i][1];
}
else if(now.step%2==0&&(i==0||i==1))
{
next.x=next.x+dir[i][0];
next.y=next.y+dir[i][1];
}
else
{
next.x=next.x+dir[i][0];
next.y=next.y+dir[i][1];
vis[next.x][next.y]=1;
next.step=now.step+2;
q.push(next);
continue;
}
}
vis[next.x][next.y]=1;
next.step=now.step+1;
q.push(next);
}
}
return ;
}
int main()
{
while(cin>>m>>n)
{
memset(vis,0,sizeof(vis));
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
cin>>map[i][j];
if(map[i][j]=='*')
vis[i][j]=1;
if(map[i][j]=='S')
{
sx=i;
sy=j;
}
}
bfs();
}
return 0;
}