诡异的楼梯 hdu 1180

来源:互联网 发布:观山4字能值多少钱知乎 编辑:程序博客网 时间:2024/06/05 14:32

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

Hint

Hint 地图如下:         
          
#include<stdio.h>#include<queue>#include<cstring>using namespace std;char map[25][25];int m,n,x1,y1,x2,y2;int visit[25][25];int dx[4]= {0,0,1,-1};int dy[4]= {-1,1,0,0};struct node{    int x,y,time;    friend bool operator<(node n1,node n2)    {        return n1.time>n2.time;    }} t;bool check(node no){    if(no.x<0||no.y<0||no.x>=n||no.y>=m||map[no.x][no.y]=='*'||(visit[no.x][no.y]&&no.time>=visit[no.x][no.y]))        return false;    return true;}int bfs(){    t.x=x1;    t.y=y1;    t.time=0;    visit[t.x][t.y]=1;    priority_queue<node>q;    while(!q.empty())        q.pop();    q.push(t);    while(!q.empty())    {        node past=q.top();        node next;        q.pop();        for(int i=0; i<4; i++)        {            next.x=past.x+dx[i];            next.y=past.y+dy[i];            next.time=past.time+1;            if(!check(next))                continue;            if(map[next.x][next.y]=='|')            {                if(next.x==past.x&&(past.time&1)==0)                    next.time++;                if(next.y==past.y&&(past.time&1)==1)                    next.time++;                next.x+=dx[i];                next.y+=dy[i];            }            else if(map[next.x][next.y]=='-')            {                if(next.x==past.x&&(past.time & 1)==1)                    next.time++;                if(next.y==past.y&&(past.time&1)==0)                    next.time++;                next.x+=dx[i];                next.y+=dy[i];            }            if(!check(next))                continue;            if(map[next.x][next.y]=='T')                return next.time;            visit[next.x][next.y]=next.time;            q.push(next);        }    }    return 0;}int main(){    while(scanf("%d%d",&n,&m)!=EOF)    {        for(int i=0; i<n; i++)        {scanf("%s",map[i]);            for(int j=0; j<m; j++)            {                if(map[i][j]=='S')                {                    x1=i;                    y1=j;                    break;                }            }        }        memset(visit,0,sizeof(visit));        int ans;        ans=bfs();        printf("%d\n",ans);    }}

0 0