经典的bfs
#include<stdio.h>
#include<string.h>
int n,m;
int prison[200][200];
char map[200][200];
int visited[200][200];
struct point{
int x,y,t;
point* pre;
}queue[20000];
int dx[4]={0,0,-1,1};
int dy[4]={-1,1,0,0};
bool check(int x,int y)
{
if(x>=0&&x<n&&y>=0&&y<m&&visited[x][y]==0&&map[x][y]!='X')
{
return true;
}
return false;
}
void output(point p)
{
if(p.pre==NULL)
return;
else
{
output(*p.pre);
if(p.pre->x==p.x&&p.pre->y==p.y)
printf("%ds:FIGHT AT (%d,%d)\n",p.t,p.x,p.y);
else
printf("%ds:(%d,%d)->(%d,%d)\n",p.t,p.pre->x,p.pre->y,p.x,p.y);
}
}
void bfs()
{
int front =0,rear=1;
queue[front].t=0;
queue[front].x=0;
queue[front].y=0;
queue[front].pre=NULL;
while(front<rear)
{
if(prison[queue[front].x][queue[front].y]>0)
{
prison[queue[front].x][queue[front].y]--;
queue[rear].x=queue[front].x;
queue[rear].y=queue[front].y;
queue[rear].t=queue[front].t+1;
queue[rear].pre=&queue[front];
front++;
rear++;
continue;
}
for(int i=0;i<4;i++)
{
int xx=queue[front].x+dx[i];
int yy=queue[front].y+dy[i];
if(check(xx,yy))
{
visited[xx][yy]=-2;
queue[rear].x=xx;
queue[rear].y=yy;
queue[rear].t=queue[front].t+1;
queue[rear].pre=&queue[front];
if(xx==n-1&&yy==m-1)
{
front=rear;
while(prison[xx][yy]>0)
{
rear++;
queue[rear].x=queue[front].x;
queue[rear].y=queue[front].y;
queue[rear].t=queue[front].t+1;
queue[rear].pre=&queue[front];
prison[xx][yy]--;
front=rear;
}
if(prison[xx][yy]==0)
{
printf("It takes %d seconds to reach the target position, let me show you the way.\n",queue[front].t);
output(queue[rear]);
printf("FINISH\n");
return;
}
}
rear++;
}
}
front++;
}
printf("God please help our poor hero.\n");
printf("FINISH\n");
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
{
scanf("%*c");
for(int j=0;j<m;j++)
{
scanf("%c",&map[i][j]);
if(map[i][j]=='.')
prison[i][j]=0;
else if(map[i][j]=='X')
prison[i][j]=-1;
else
prison[i][j]=map[i][j]-'0';
}
}
memset(visited,0,sizeof(visited));
bfs();
}
return 0;
}