HDU 1242 bfs优先队列
http://acm.hdu.edu.cn/showproblem.php?pid=1242
Angel所在的位置是a; Angel的朋友用r表示, Angel可能有多个朋友 ,也就是可能有多个r ; #表示墙 ;x表示警卫 ,可能会有多个警卫;
Angel的朋友要进入a 只能上下左右的走, 每走一个格用一个单位时间,如果遇上警卫,杀掉警卫要花一个单位时间 问Angel能否救到angel,
如果能 求最少的时间
被这道题的有两个地方震了 1.有多个r 搜r到a有多条路 最后比较 但是倒过来想 从a搜到r就搜一条最佳路
2.涉及到一个杀警卫的时间,所以queue队列中的node 不是按时间大小排列的, 用到priority_queue,
第一学着次用priority_queue, 在此感谢cxl
代码:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
char map[202][202];
int n,m,bx,by;
int XX[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
int x,y,step;
friend bool operator < (node t1,node t2)
{
return t1.step>t2.step;
}
};
void bfs(int bx,int by)
{
priority_queue<node>qu;
node t;
int k;
t.x=bx,t.y=by,t.step=0;
qu.push(t);
while(!qu.empty())
{
t=qu.top();
qu.pop();
for(k=0;k<4;k++)
{
node tt=t;tt.step++;
tt.x+=XX[k][0],tt.y+=XX[k][1];
if(tt.x<1||tt.x>n||tt.y<1||tt.y>m||map[tt.x][tt.y]=='#')
continue;
else
if(map[tt.x][tt.y]=='r')
{
cout<<tt.step<<endl;
return;
}
else
if(map[tt.x][tt.y]=='x')
tt.step++;
map[tt.x][tt.y]='#';
qu.push(tt);
}
}
cout<<"Poor ANGEL has to stay in the prison all his life.\n";
return ;
}
int main()
{
int i,j;
while(cin>>n>>m)
{
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
cin>>map[i][j];
if(map[i][j]=='a')
bx=i,by=j;
}
bfs(bx,by);
}
return 0;
}

浙公网安备 33010602011771号