注意:深搜超时
思路:使用广搜和优先队列。首先初始化数组,将不能到达的地方(即X)置为-1;将怪兽所在的地方转换成数字,将“ .”置为0;在广搜的时候如果已经访问过将其置为-1,不能再次访问。广搜找到合适路径,并保存路径
#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
struct node
{
int x,y;
int time;
friend bool operator<(node n1,node n2)
{
return n2.time<n1.time;
}
};
int dir[4][2]={0,1, 1,0, 0,-1, -1,0};
int a[101][101];
int flag[101][101];
int monster[101][101];
int n,m;
int BFS()
{
//定义优先队列
priority_queue<node>q;
//结构体重命名
node cur,next;
int i;
//a[0][0]初始化
cur.x=0;
cur.y=0;
cur.time=0;
a[0][0]=-1;
//入队列
q.push(cur);
while(!q.empty())
{
//cur为队首的元素
cur=q.top();
//队首出队列
q.pop();
//找到公主,返回
if(cur.x==n-1 && cur.y==m-1) return cur.time;
for(i=0;i<4;i++)
{
next.x=cur.x+dir[i][0];
next.y=cur.y+dir[i][1];
//判断是否越界以及是否访问过
if(next.x<0||next.y<0||next.x>=n||next.y>=m||a[next.x][next.y]==-1) continue;
//如果此处点为怪兽,加上怪兽的怪兽值a[next.x][next.y],反则加0
next.time=cur.time+1+a[next.x][next.y];
//存储路径
flag[next.x][next.y]=i+1;
//将这个点标记为-1,表示已经走过
a[next.x][next.y]=-1;
//将这个点入队列
q.push(next);
}
}
return -1;
}
int temp;
//输出函数
void P(int x,int y)
{
int next_x,next_y;
if(flag[x][y]==0) return ;
next_x=x-dir[flag[x][y]-1][0];
next_y=y-dir[flag[x][y]-1][1];
P(next_x,next_y);
printf("%ds:(%d,%d)->(%d,%d)\n",temp++,next_x,next_y,x,y);
while(monster[x][y]--) printf("%ds:FIGHT AT (%d,%d)\n",temp++,x,y);
}
int main()
{
char str[111];
int i,l;
int ans;
while(scanf("%d%d",&n,&m)!=-1)
{
memset(a,0,sizeof(a));
memset(flag,0,sizeof(flag));
memset(monster,0,sizeof(monster));
for(i=0;i<n;i++)
{
scanf("%s",str);
for(l=0;str[l];l++)
{
if(str[l]=='.') a[i][l]=0;
else if(str[l]=='X')a[i][l]=-1;
else a[i][l]=monster[i][l]=str[l]-'0';
}
}
//ans表示时间
ans=BFS();
if(ans==-1) printf("God please help our poor hero.\n");
else
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",ans);
temp=1;
P(n-1,m-1);
}
printf("FINISH\n");
}
return 0;
}