69,369
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define max 201
#define maxsize 40005
typedef struct
{
int x,y;
}Queue;
char graph[max][max];
int step[max][max];
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int bfs(int n,int m,Queue np);
int main()
{
int n,m;
Queue np;
while(scanf("%d%d%*c",&n,&m)!=EOF)
{
memset(graph,0,sizeof(graph));
memset(step,0,sizeof(step));
int i,j;
for(i=0;i<n;i++)
{
gets(graph[i]);
for(j=0;j<m;j++)
if(graph[i][j]=='a')
{
np.x=i;
np.y=j;
}
}
int res=bfs(n,m,np);
if(res)
printf("%d\n",res);
else
printf("Poor ANGEL has to stay in the prison all his life.\n");
}
return 0;
}
int bfs(int n,int m,Queue np)
{
Queue q[maxsize],cp;
int res=0,front,rear,i;
front=rear=0;
q[rear++]=np;
step[np.x][np.y]=0;
while(front<rear)
{
np=q[front++];
for(i=0;i<4;i++)
{
cp.x=np.x+dir[i][0];
cp.y=np.y+dir[i][1];
if(cp.x>=0&&cp.x<n&&cp.y>=0&&cp.y<m&&graph[cp.x][cp.y]!='#')
{
if((step[cp.x][cp.y]>step[np.x][np.y]+1)||step[cp.x][cp.y]==0)
{
step[cp.x][cp.y]=step[np.x][np.y]+1;
q[rear++]=cp;//入队
}
if(graph[cp.x][cp.y]=='r')
{
res=step[cp.x][cp.y];
}
if(graph[cp.x][cp.y]=='x')
{
step[cp.x][cp.y]++;
}
}
}
}
return res;
}