AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
struct node
{
int x,y,time;
friend bool operator < (node a,node b)
{
return a.time>b.time;
}
};
struct point
{
int x,y;
}pri[110][110];
char map1[110][110],ch;
int book[110][110],n,m,nex[4][2]={0,1,1,0,0,-1,-1,0},kt;
priority_queue<node> q;
bool pan(int x,int y)
{
if(x<0||x>=n||y<0||y>=m)
return true;
return false;
}
void print(int x,int y,int time) //输出路径
{
if(x==0 && y==0)
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",time);
if(map1[0][0]>='0' && map1[0][0]<='9') //入口有怪物的时候
for(int i=0;i<map1[0][0]-'0';i++)
printf("%ds:FIGHT AT (%d,%d)\n",kt++,0,0);
return ;
}
print(pri[x][y].x,pri[x][y].y,time);
printf("%ds:(%d,%d)->(%d,%d)\n",kt++,pri[x][y].x,pri[x][y].y,x,y);
if(map1[x][y]>='0' && map1[x][y]<='9')
for(int i=0;i<map1[x][y]-'0';i++)
printf("%ds:FIGHT AT (%d,%d)\n",kt++,x,y);
return ;
}
bool bfs(int x,int y,int st)
{
while(!q.empty())
q.pop();
book[x][y]=1;
int i;
node now,xia;
now.x=x;
now.y=y;
now.time=st;
q.push(now);
pri[x][y].x=x;
pri[x][y].y=y;
while(!q.empty())
{
now=q.top();
q.pop();
if(now.x==n-1 && now.y==m-1)
{
print(n-1,m-1,now.time);
return true;
}
for(i=0;i<4;i++)
{
xia.x=now.x+nex[i][0];
xia.y=now.y+nex[i][1];
ch=map1[xia.x][xia.y];
if( pan(xia.x,xia.y) || ch=='X' || book[xia.x][xia.y]) continue;
if(ch=='.')
{
xia.time=now.time+1;
}
else if(ch>='0' && ch<='9')
{
xia.time=now.time+1+ch-'0';
}
pri[xia.x][xia.y].x=now.x;
pri[xia.x][xia.y].y=now.y;
book[xia.x][xia.y]=1;
q.push(xia);
/*
*******为什么可以省略?
由于是优先队列,每次都是把到达下一点的最
小权的路个它,比其权大的优先级一定比它小
*******
else if(pri[xia.x][xia.y].time>now.time)
{
pri[xia.x][xia.y]=now;
}
else //如果到达该点的时间没比上次到达这点的时间短也就不必要把这点入队
continue;
q.push(xia);
*/
}
}
return false;
}
int main()
{
int i,j,ks=1;
// freopen("e:\\input.txt","r",stdin);
// freopen("e:\\output.txt","w",stdout);
while(~scanf("%d%d",&n,&m))
{
getchar();
memset(book,0,sizeof(book));
memset(pri,0,sizeof(pri));
for(i=0;i<n;i++)
scanf("%s",map1[i]);
kt=1;
//printf("data %d :\n",ks++);
if(!bfs(0,0,0))
{
printf("God please help our poor hero.\n");
}
cout<<"FINISH"<<endl;
// cout<<endl;
}
return 0;
}