原题:
传送门
题意:
#的格子不能走;. 的可以走,要1个单位时间;x 的格子也可以走,不过要2个单位时间,求从r到a的最小时间
思路:
bfs搜索
注意:
不同于传统的bfs,这次走一个格子的时间可以是1或2,所以使用priority_queue<node>
来存储,记得再结构体内重载<运算符,使得默认大根堆的优先队列变为小根堆
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int dr[4][2]={1,0,0,1,-1,0,0,-1};
bool vis[202][202];
char mp[203][203];
int n, m;
int nx, ny;
struct node {
int x, y, step;
friend bool operator < (node a, node b) {
return a.step>b.step;
}
};
priority_queue<node> q;
node nd;
int bfs(int x, int y) {
nd.x=x;
nd.y=y;
nd.step=0;
q.push(nd);
vis[x][y]=true;
while (!q.empty()) {
node u=q.top();q.pop();
if (mp[u.x][u.y] == 'a') {
return u.step;
}
for (int i=0;i<4;i++) {
nx = u.x + dr[i][0];
ny = u.y + dr[i][1];
if ((nx>=0&&nx<n) && (ny>=0&&ny<m) && !vis[nx][ny] && mp[nx][ny]!='#') {
nd.x=nx;
nd.y=ny;
nd.step = u.step + (mp[nx][ny]=='x'?2:1);
q.push(nd);
vis[nx][ny] = true;
}
}
}
return -1;
}
void init() {
while (!q.empty()) {
q.pop();
}
}
int main()
{
int fx, fy;
while (cin>>n>>m) {
init();
for (int i=0;i<n;i++)
for (int j=0;j<m;j++) {
vis[i][j]=false;
cin>>mp[i][j];
if (mp[i][j] == 'r') {
fx = i;
fy = j;
}
}
int ans=bfs(fx, fy);
if (ans==-1) {
cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
} else {
cout<<ans<<endl;
}
}
return 0;
}