需要在监狱里营救出天使,监狱里有若干个狱卒,干掉狱卒需要消耗1回合。特别注意营救者可能不止一个。
因为干掉狱卒需要多消耗1回合,所以用简单的队列出来的不一定就是最优结果,所以要用到优先队列。
BFS与优先队列的应用。
#include<iostream>
#include<string>
#include<queue>
using namespace std;
int **Prison;
int n,m;
int move[4][2] = {{-1,0},{0,-1},{0,1},{1,0}};
struct Point{
int x;
int y;
int steps;
}start;
priority_queue<Point> q;
bool operator<(const Point &a,const Point &b){
//优先递增队列
if(a.steps > b.steps)return true;
return false;
}
void Create(){
//初始化监狱
string s;
int i,j;
Prison = new int*[n + 2];
for(i=0; i<n+2; i++){
Prison[i] = new int[m+2];
}
for(i=0; i<n+2; i++){
Prison[i][0] = Prison[i][m+1] = 1;
}
for(j=0; j<m+2; j++){
Prison[0][j] = Prison[n+1][j] = 1;
}
for(i=1; i<=n; i++){
cin>>s;
for(j=1; j<=m; j++){
switch(s[j-1]){
case '.':Prison[i][j] = 0;break;
case '#':Prison[i][j] = 1;break;
case 'a':Prison[i][j] = 9;break;
case 'r':Prison[i][j] = 8;start.x = i;start.y = j;start.steps = 0;q.push(start);break;
case 'x':Prison[i][j] = 5;break;
}
}
}
}
int BFS(){
//寻找最短路径并输出步数
while(!q.empty()){
start = q.top();
q.pop();
for(int i=0; i<4; i++){
Point temp;
temp.x = start.x + move[i][0];
temp.y = start.y + move[i][1];
temp.steps = start.steps + 1;
if(Prison[temp.x][temp.y] == 9)return temp.steps;
if(Prison[temp.x][temp.y] == 0){
Prison[temp.x][temp.y] = 8;
q.push(temp);
}
if(Prison[temp.x][temp.y] == 5){
Prison[temp.x][temp.y] = 8;
temp.steps ++;
q.push(temp);
}
}
}
return -1;
}
int main(){
while(cin>>n>>m){
Create();
int steps = BFS();
if(steps == -1) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
else cout<<steps<<endl;
while(!q.empty())q.pop();
}
return 0;
}