在使用優先隊列時, 不僅可按元素的大小爲優先級,在使用結構體時,可通過運算符重載
在其他的博客看到一句話,優先隊列是隊列和排序的結合,很精闢
本題因爲經過守衛和道路時所花的時間不一樣,故不能用簡單的隊列求解,可使用優先隊列,到達該點時間少的先出隊列
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
struct node
{
int x, y, t;
friend bool operator < (const node a, const node b)
{
return a.t > b.t;
}
};
int dx[] = {0, 0, 0, -1, 1};
int dy[] = {0, -1, 1, 0, 0};
int vis[210][210], n, m;
char maze[210][210];
int bfs(int x, int y)
{
node a, b;
priority_queue<node> q;
while(!q.empty()) q.pop();
a.x = x, a.y = y, a.t = 0;
q.push(a);
vis[x][y] = 1;
while(!q.empty())
{
a = q.top();
q.pop();
if(maze[a.x][a.y] == 'r')
return a.t;
for(int i=1; i<=4; i++)
{
b.x = a.x + dx[i];
b.y = a.y + dy[i];
if(!vis[b.x][b.y] && b.x>=1 && b.x<=n && b.y>=1 && b.y<=m && maze[b.x][b.y]!='#')
{
vis[b.x][b.y] = 1;
if(maze[b.x][b.y] == 'x')
b.t = a.t + 2;
else
b.t = a.t + 1;
q.push(b);
}
}
}
return -1;
}
int main()
{
while(scanf("%d %d", &n, &m) == 2)
{
int sx, sy;
for(int i=1; i<=n; i++)
scanf("%s", maze[i] + 1);
for(int i=1; i<=n; i++)
for(int j=1; j<=m; j++)
{
vis[i][j] = 0;
if(maze[i][j] == 'a')
{
sx = i;
sy = j;
}
}
int ans= bfs(sx, sy);
if(ans == -1)
printf("Poor ANGEL has to stay in the prison all his life.\n");
else
printf("%d\n", ans);
}
return 0;
}