题目:http://acm.hdu.edu.cn/showproblem.php?pid=1242
如果往个放向每走一步的代价不一样的话,bfs要用优先队列
#include<bits/stdc++.h>
using namespace std;
int n,m;
char maze[205][205];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
bool vis[205][205];
struct node{
int x,y,step;
bool operator < (const node &a)const{
return a.step<step;
}
node(int x,int y,int step):x(x),y(y),step(step){
} ;
};
int bfs(int x,int y,int step){
vis[x][y]=true;
priority_queue<node> que;
que.push(node(x,y,0));
while(!que.empty()){
node now=que.top();
que.pop();
if(maze[now.x][now.y]=='r'){
return now.step;
}
for(int i=0;i<4;i++){
int x=now.x+dir[i][0];
int y=now.y+dir[i][1];
int step=now.step+1;
if(x>=0&&y>=0&&x<n&&y<m&&maze[x][y]!='#'&&!vis[x][y]){
vis[x][y]=true;
if(maze[x][y]=='x'){
step+=1;
}
que.push(node(x,y,step));
}
}
}
return -1;
}
int main(){
while(~scanf("%d%d",&n,&m)){
memset(vis,false,sizeof(vis));
for(int i=0;i<n;i++){
scanf("%s",maze[i]);
}
int ans;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(maze[i][j]=='a'){
ans=bfs(i,j,0);
break;
}
}
}
if(ans==-1){
printf("Poor ANGEL has to stay in the prison all his life.\n");
}else{
printf("%d\n",ans);
}
}
return 0;
}