hdu 1180 诡异的楼梯(优先队列)

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


        
  
地图如下:

#include<queue>
#include<stack>
#include<math.h>
#include<stdio.h>
#include<numeric>//STL数值算法头文件
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<functional>//模板类头文件
using namespace std;


//走楼梯的时候偶数步楼梯改变,奇数不改变,并且在楼梯上不花费时间
char map[25][25];
bool vis[25][25];
int n,m,sx,sy;

int dir[4][2] = {0,1,1,0,0,-1,-1,0};

struct node
{
    int x, y,step;
    friend bool operator < (const node &a, const node &b)
    {
        return a.step > b.step;
    }
};
int go(int x, int y)
{
    if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&map[x][y]!='*')
        return 1;
    return 0;
}

int bfs(int x, int y)
{
    char c;
    priority_queue <node> q;
    node st,ed;
    st.x = x;
    st.y = y;
    st.step = 0;
    vis[st.x][st.y]=1;
    q.push(st);
    while(!q.empty())
    {
        st=q.top();
        q.pop();
        for(int i = 0; i < 4; i ++)
        {
            ed.x=st.x+dir[i][0];
            ed.y=st.y+dir[i][1];
            ed.step=st.step+1;
            if(go(ed.x,ed.y)&&(map[ed.x][ed.y]=='-'||map[ed.x][ed.y]=='|'))
            {
                if(ed.step%2==1)//到达楼梯的时候,步数为偶数则楼梯改变,否则不改变
                {
                    if(map[ed.x][ed.y]=='-') c = '|';//过去之后楼梯改变
                    else if(map[ed.x][ed.y]=='|') c = '-';
                }
                else c=map[ed.x][ed.y];
                ed.x+=dir[i][0];
                ed.y+=dir[i][1];
                if((c=='-'&&(dir[i][1]==-1||dir[i][1]==1))||(c=='|'&&(dir[i][0]==-1||dir[i][0]==1)))
                {
                    ed.step += 1;
                }
            }
            if(go(ed.x, ed.y))//过楼梯之后
            {
                if(map[ed.x][ed.y] == 'T') return ed.step;
                vis[ed.x][ed.y] = 1;
                q.push(ed);
            }
        }
    }
    return -1;
}

int main()
{
    while(~scanf("%d %d", &n, &m))
    {
        for(int i = 0; i < n; i ++)
            for(int j = 0; j < m; j ++)
            {
                cin>>map[i][j];
                if(map[i][j]=='S')
                {
                    sx=i;
                    sy=j;
                }
            }
        memset(vis,0,sizeof(vis));
        printf("%d
",bfs(sx, sy));
    }
    return 0;
}





原文地址:https://www.cnblogs.com/nyist-xsk/p/7264882.html