问题 H: 逃出迷宫
时间限制: 1 Sec 内存限制: 128 MB提交: 6 解决: 3
[ 提交][ 状态][ 讨论版]
题目描述
现在有一个迷宫,'a'代表起点位置,'.'代表可以通行的路,'#'代表不能通过的墙,'x'代表迷宫的守卫,'r'代表终点位置,
现在要求你算出起点位置到终点位置的最短时间,其中通过'.'时,消耗1个单位时间,通过'x'消耗两个单位时间。
现在要求你算出起点位置到终点位置的最短时间,其中通过'.'时,消耗1个单位时间,通过'x'消耗两个单位时间。
输入
多组测试数据,输入两个整数(X,Y)代表迷宫的长和宽,之后输入迷宫。
输出
如果可以到达终点,输出到达终点的最短时间。如果不能到达终点输出"Oh No!"。
样例输入
7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........
样例输出
13
提示
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<queue>
using namespace std;
char a[500][500];
struct node
{
int x,y,step;
friend bool operator<(node a,node b)
{
return a.step>b.step;//“>"是步数少的先出队,"<"步数大的先出队
}
}s,e;
int n,m;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
void bfs()
{
priority_queue<node>q;
node temp,t;
q.push(s);
a[s.x][s.y]='#';
while(!q.empty())
{
temp=q.top();
q.pop();
if(temp.x==e.x&&temp.y==e.y)
{
cout<<temp.step<<endl;
return;
}
for(int i=0;i<4;i++)
{
t.x=temp.x+dir[i][0];
t.y=temp.y+dir[i][1];
if(t.x>=0&&t.x<n&&t.y>=0&&t.y<m&&a[t.x][t.y]!='#')//满足条件的进队,步数少的先出队,所以要用优先队列
{
if(a[t.x][t.y]=='x')
t.step=temp.step+2;
else
t.step=temp.step+1;
a[t.x][t.y]='#';
q.push(t);
}
}
}
cout<<"Oh No!"<<endl;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
int i,j;
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.step=0;
}
if(a[i][j]=='r')
{
e.x=i;
e.y=j;
}
}
bfs();
}
}