题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242
分析
这道题可以采用bfs+优先队列。
注意两点:
1.天使的朋友可能不只一个,所以应该从天使的位置开始找其朋友
2.用普通的队列可能得不到最优的答案,需要用优先队列,将花费时间少的排在前面
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
#define N 300 + 10
int n,m;
char a[N][N];
int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct Node {
int x,y,t;
bool operator < (const Node& b) const {
return t > b.t;
}
};
bool isValid(int x,int y)
{
return (x >= 0) && (x < n) && (y >= 0) && (y < m) && (a[x][y] != '#');
}
bool bfs(int x,int y)
{
Node start = {x,y,0};
priority_queue<Node> q;
q.push(start);
a[x][y] = '#';
while(!q.empty()) {
Node head = q.top();
q.pop();
for(int i = 0; i < 4; i++) {
int nx = head.x + dir[i][0];
int ny = head.y + dir[i][1];
if(isValid(nx,ny)) {
int t = head.t + 1;
if(a[nx][ny] == 'r') {
printf("%d\n",t);
return true;
}
if(a[nx][ny] == 'x') t++;
a[nx][ny] = '#';
Node node = {nx,ny,t};
q.push(node);
}
}
}
return false;
}
int main()
{
while(scanf("%d%d",&n,&m) != EOF) {
int x,y;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++) {
scanf(" %c",&a[i][j]);
if(a[i][j] == 'a') x = i,y = j;
}
if(!bfs(x,y)) printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}