# 优先队列+BFS

#include<iostream>
#include<queue>
using namespace
std;
#define MAXN 205
char map[MAXN][MAXN];
int
N,M,starti,startj;
int
dir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
struct
love
{

int
x,y;
int
time;
friend
bool operator<(love a,love b){
return
a.time>b.time;
}//按权值从小到大排

};

int BFS(int nowi,int nowj,int step)
{

priority_queue <love> Q;
love first,next;
first.x=nowi;
first.y=nowj;
first.time=step;
Q.push(first);
int
fx,fy;
while
(!Q.empty()){
first=Q.top();
Q.pop();
for
(int i=0;i<4;i++){
fx=dir[i][0]+first.x;
fy=dir[i][1]+first.y;
if
(fx>=0&&fx<N&&fy>=0&&fy<M&&map[fx][fy]!=‘#’){
if
(map[fx][fy]==‘r’){
return
first.time+1;
}

else if
(map[fx][fy]==‘.’){
next.time=first.time+1;
}

else if
(map[fx][fy]==‘x’){
next.time=first.time+2;
}

next.x=fx;
next.y=fy;
map[next.x][next.y]=‘#’;
Q.push(next);
}
}
}

return
1;
}

int
main()
{

int
i,j;
while
(cin>>N>>M)
{

for
(i=0;i<N;i++){
for
(j=0;j<M;j++){
cin>>map[i][j];
if
(map[i][j]==‘a’){
starti=i;
startj=j;
}
}
}

int
ans=BFS(starti,startj,0);
if
(ans==-1)
printf(“Poor ANGEL has to stay in the prison all his life./n” );
else

printf(“%d/n”,ans);
}
}

原文作者：BFS
原文地址: https://blog.csdn.net/monkey_little/article/details/6221098
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。