逃出迷宫 优先队列

逃出迷宫

时间限制: 1 Sec 内存限制: 128 MB
提交: 24 解决: 12

题目描述
现在有一个迷宫,’a’代表起点位置,’.’代表可以通行的路,’#’代表不能通过的墙,’x’代表迷宫的守卫,’r’代表终点位置,
现在要求你算出起点位置到终点位置的最短时间,其中通过’.’时,消耗1个单位时间,通过’x’消耗两个单位时间。
输入
多组测试数据,输入两个整数(X,Y)代表迷宫的长和宽,之后输入迷宫。
输出
如果可以到达终点,输出到达终点的最短时间。如果不能到达终点输出”Oh No!”。
样例输入
7 8
#.#####.
#.a#..r.
#..#x…
..#..#.#
#…##..
.#……
……..
样例输出
13
因为再有守卫的情况下 通过 需要 消耗俩个单位时间 所以要对时间进行排序     优先队列 

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct node
{
    friend bool operator<(node a1,node a2)//对优先时间进行排序
    {
        return a1.time>a2.time;
    }
    int x,y,time;
}s,e;
int n,m,i,j;
char a[100][100];
int b[100][100];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs()
{
    priority_queue<node>q;//优先队列 
    node t,x1;
    q.push(s);
    while(!q.empty())
    {
        t=q.top();
        q.pop();
        b[t.x][t.y]=1;
        if(a[t.x][t.y]=='r')//但为 r 结束
        {
            cout<<t.time<<endl;
            return ;
        }
        for(i=0;i<4;i++)  //   是四个方向 走
        {
            x1.time=t.time+1;
            x1.y=t.y+dir[i][1];
            x1.x=t.x+dir[i][0];
            if(a[x1.x][x1.y]=='#'||x1.x<0||x1.x>n||x1.y<0||x1.y>m||b[x1.x][x1.y]==1)
                continue;
            else if(a[x1.x][x1.y]=='x')
                x1.time++;
            q.push(x1);  //入队
            b[x1.x][x1.y]=1; // 标记走过的路
        }
    }
    cout<<"Oh No!"<<endl;
}
int main()
{
    while(cin>>n>>m)
    {
        memset(b,0,sizeof(b));
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                cin>>a[i][j];
                if(a[i][j]=='a')
                {
                    s.x=i;
                    s.y=j;
                    s.time=0;
                }
            }
        }
        bfs();
    }
    return 0;
}
原文地址:https://www.cnblogs.com/nanfenggu/p/7900198.html