问题链接:Problem G
问题简述:
公主在地图中的右下角,勇士在地图中的右上角,地图中的数字代表当前位置怪物的血量,若勇士碰上了怪物,需要消耗相应血量的时间。问勇士能否救到公主?若能,输出最短时间与路径。
问题分析:
搜索最短路径问题,要用到BFS算法。本题的难点有二:
1.记录路径并输出
2.对怪物的处理
解决难点1可以在结构中定义数组,在每次移动中记录坐标即可。解决难点二时,可以将直接将时间=之前所花费的时间+怪物的血量+1,再压入队列。但是!特别要注意的是在普通队列中,由于压入队列的时间不一致,因此所得的答案就不一定是最优答案了。因此需要用到优先队列,让时间较小的队列先出列,就解决了这个问题。
程序说明:
注意用优先队列时,取最上方队列是q.top()而非q.front().
AC通过的C语言程序如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
int n,m;
char map[105][105];
bool vis[105][105];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct node{
int x,y,step;
int route[905][2];
friend bool operator <(node a,node b){
return a.step>b.step;
}
};
bool edge(int x,int y){
if(x>=0&&y>=0&&x<n&&y<m&&map[x][y]!='X'&&vis[x][y]==0)
return 1;
else{
return 0;
}
}
node BFS(){
priority_queue<node>q;
node p1;
p1.x=0;
p1.y=0;
p1.step=0;
p1.route[0][0]=0;
p1.route[0][1]=0;
vis[0][0]=1;
q.push(p1);
while(!q.empty()){
node p2=q.top();
q.pop();
if(p2.x==n-1&&p2.y==m-1){
return p2;
}
for(int i=0;i<4;i++){
int next_x=p2.x+dir[i][0];
int next_y=p2.y+dir[i][1];
if(edge(next_x,next_y)){
if(map[next_x][next_y]!='.'){
vis[next_x][next_y]=1;
p1=p2;
p1.x=next_x;
p1.y=next_y;
p1.step=1+p2.step+map[next_x][next_y]-'0';
for(int i=p2.step+1;i<=p1.step;i++){
p1.route[i][0]=next_x;
p1.route[i][1]=next_y;
}
q.push(p1);
}
else{
vis[next_x][next_y]=1;
p1=p2;
p1.x=next_x;
p1.y=next_y;
p1.step=1+p2.step;
p1.route[p1.step][0]=next_x;
p1.route[p1.step][1]=next_y;
q.push(p1);
}
}
}
}
p1.step=-1;
return p1;
}
int main(){
std::ios::sync_with_stdio(false);
while(cin>>n>>m){
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>map[i][j];
}
}
node ans=BFS();
if(ans.step==-1){
cout<<"God please help our poor hero."<<endl;
cout<<"FINISH"<<endl;
}
else{
cout<<"It takes "<<ans.step<<" seconds to reach the target position, let me show you the way."<<endl;
for(int i=1;i<=ans.step;i++){
if(ans.route[i][0]!=ans.route[i-1][0]||ans.route[i][1]!=ans.route[i-1][1]){
cout<<i<<"s:("<<ans.route[i-1][0]<<","<<ans.route[i-1][1]<<")->("<<ans.route[i][0]<<","<<ans.route[i][1]<<")"<<endl;
}
else{
cout<<i<<"s:"<<"FIGHT AT ("<<ans.route[i][0]<<","<<ans.route[i][1]<<")"<<endl;
}
}
cout<<"FINISH"<<endl;
}
}
}