题目大意:解救公主,开始位置在(0,0)出口在(n-1,m-1),迷宫中有怪物,对应的数字即为需要在此停留的时间,'.'为可走的路,'X'为墙不可走,问是否可以走出迷宫?如果可以,需要的最少的时间,以及走出迷宫的路径。
解题思路:BFS+优先队列+路径记录
#include<stdio.h>
#include<iostream>
#include<queue>
#include<stack>
#include<string.h>
using namespace std;
char Map[150][150];
bool flag[150][150];
int f[4][2]= {{-1,0},{0,1},{1,0},{0,-1}};
int ans;
struct node
{
int x;
int y;
int step;
node ()
{
x=0;
y=0;
step=1;
}
bool operator <(const node &a)const //按step从小到大排列
{
return a.step<step;
}
};
node st,en;
node mem[150][150];
int bfs(int nn,int mm)
{
st.x=0,st.y=0;
st.step=0;
flag[0][0]=1;
priority_queue<node>q;
q.push(st);
while(!q.empty())
{
node tmp,temp=q.top();
// cout<<temp.x<<" "<<temp.y<<" "<< temp.step<<endl;
if(temp.x==nn&&temp.y==mm)
{
return temp.step;
}
for(int i=0; i<4; i++)
{
tmp.x=temp.x+f[i][0];
tmp.y=temp.y+f[i][1];
tmp.step=temp.step+1;
// cout<<"tmp.step "<<tmp.step<<endl;
if(tmp.x>=0&&tmp.y>=0&&tmp.x<=nn&&tmp.y<=mm)
{
if(Map[tmp.x][tmp.y]!='X'&&flag[tmp.x][tmp.y]==0)
{
mem[tmp.x][tmp.y].x=temp.x; //记录路径,后一个记录前一个的位置
mem[tmp.x][tmp.y].y=temp.y; //
// mem[tmp.x][tmp.y].step=temp.step+1;
if(Map[tmp.x][tmp.y]=='.')
{
q.push(tmp);
}
else
{
int hp=Map[tmp.x][tmp.y]-'0';
// cout<<"hp "<<hp<<endl;
tmp.step+=hp;
q.push(tmp);
}
flag[tmp.x][tmp.y]=1;
}
}
}
q.pop();
}
return -1;
}
void prin(int an,int nnn,int mmm)
{
int tt=0;
if(an==-1)
{
cout<<"God please help our poor hero."<<endl<<"FINISH"<<endl;
}
else
{
cout<<"It takes "<<an<<" seconds to reach the target position, let me show you the way."<<endl;
stack<node>p;
node tmp=mem[nnn][mmm];
// cout<<nnn<<" "<<mmm<<endl;
// cout<<mem[nnn][mmm].x<<" "<<mem[nnn][mmm].y<<endl;
node tmmp;
tmmp.x=nnn,tmmp.y=mmm,tmmp.step=an; //把出口入栈
p.push(tmmp);
while(tmp.x!=0||tmp.y!=0)
{
p.push(tmp);
// cout<<tmp.x<<" "<<tmp.y<<endl;
// getchar();
tmp=mem[tmp.x][tmp.y];
} //把入口的后一个结构体入栈
while(!p.empty())
{
tmp=p.top();
p.pop();
// cout<<"x "<<tmp.x<<"y "<<tmp.y<<endl;
if(Map[tmp.x][tmp.y]=='.')
{ //前一个坐标 //后一个坐标
printf("%ds:(%d,%d)->(%d,%d)\n",++tt,mem[tmp.x][tmp.y].x,mem[tmp.x][tmp.y].y,tmp.x,tmp.y);
}
else
{
int num=Map[tmp.x][tmp.y]-'0';
printf("%ds:(%d,%d)->(%d,%d)\n",++tt,mem[tmp.x][tmp.y].x,mem[tmp.x][tmp.y].y,tmp.x,tmp.y);
while(num--)
{
printf("%ds:FIGHT AT (%d,%d)\n",++tt,tmp.x,tmp.y);
}
}
}
cout<<"FINISH"<<endl;
}
}
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(flag,0,sizeof(flag));
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin>>Map[i][j];
}
}
ans= bfs(n-1,m-1);
prin(ans,n-1,m-1);
}
return 0;
}