#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
int n,m;
char Map[150][150];
int vis[150][150];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
typedef struct NODE
{
int x,y;
}NODE;
struct node
{
int s;
NODE now;
NODE pre;
friend bool operator <(node a,node b) //从大到小排序
{
return a.s>b.s;
}
}a[150][150];
void init() //初始化标志数组
{
memset(vis,0,sizeof(vis));
}
bool check(int x,int y) //未出界 并且 不是墙 并且 未访问
{
return !vis[x][y]&&x>=0&&y>=0&&x<n&&y<m&&(Map[x][y]!='X');
}
void print(node st)
{
cout<<"It takes "<<st.s<<" seconds to reach the target position, let me show you the way."<<endl;
NODE route[10050];
route[0]=st.now; //终点
int cnt=1;
while(st.now.x!=0||st.now.y!=0){ //把路径存在route数组中
st=a[st.pre.x][st.pre.y];
route[cnt++]=st.now;
}
int t=1; //记时
for(int i=cnt-1;i>0;i--){ //只需选在n-1个点
if(Map[route[i].x][route[i].y]!='.'){ //如果为数字
char tt=Map[route[i].x][route[i].y];
while(tt!='0'){ //数字为多少循环几次
cout<<t++<<"s:FIGHT AT ("<<route[i].x<<','<<route[i].y<<")"<<endl;
tt--;
}
}
cout<<t++<<"s:("<<route[i].x<<','<<route[i].y<<")->("<<route[i-1].x<<','<<route[i-1].y<<')'<<endl;
}
if(Map[route[0].x][route[0].y]!='.'){ //若终点为数字这种情况单独考虑
char tt=Map[route[0].x][route[0].y];
while(tt!='0'){
cout<<t++<<"s:FIGHT AT ("<<route[0].x<<','<<route[0].y<<")"<<endl;
tt--;
}
}
return;
}
void bfs()
{
priority_queue<node>q; //优先队列
node st;
st.s=0;
st.now.x=0;
st.now.y=0;
st.pre.x=0;
st.pre.y=0;
a[0][0]=st;
vis[0][0]=1;
q.push(st); //当前点入队
while(!q.empty()){
st=q.top();
q.pop();
if(st.now.x==n-1&&st.now.y==m-1){ //找到终点
print(st);
//cout<<st.s<<endl;
return;
}
for(int i=0;i<4;i++){
node nt=st;
nt.pre.x=st.now.x;
nt.pre.y=st.now.y;
nt.now.x+=dir[i][0];
nt.now.y+=dir[i][1];
if(check(nt.now.x,nt.now.y)){
vis[nt.now.x][nt.now.y]=1;
a[nt.now.x][nt.now.y]=nt;
int t=1;
if(Map[nt.now.x][nt.now.y]!='.'){
t+=Map[nt.now.x][nt.now.y]-'0';
}
nt.s+=t;
q.push(nt);
}
}
}
cout<<"God please help our poor hero."<<endl;
}
int main()
{
cin.sync_with_stdio(false); //加快cout cin的速度
while(cin>>n>>m){
init();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>Map[i][j];
}
}
bfs();
cout<<"FINISH"<<endl;
}
return 0;
}
HDOJ1026 优先队列bfs
最新推荐文章于 2019-06-11 22:14:43 发布